时间:2021-05-19
1. 注册登录
输入网址:https://mons.lang3.time.DateUtils;import org.apache.logging.log4j.util.Strings;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;import java.io.*;import java.net.URLEncoder;import java.util.Date;import java.util.HashMap;import java.util.Map;/** * @ClassName: OSSUtill * @Description: 阿里云 对象云存储工具类 * @Author: zte * @Date: 2019-02-13 14:38 * @Version 1.0 **/@Slf4jpublic class OssUtil { /** * 注入配置 */ private static OssProerties ossProerties; /** * @Title: initConfig * @Description: 配置初始化 * @Author: lxt * @param: ossProertiesInit * @Date: 2019-02-14 09:25 * @throws: */ public static void initConfig(OssProerties ossProertiesInit){ ossProerties = ossProertiesInit; } /** * @Title: generateKey * @Description: 生成oss对象名称 * @Author: lxt * @param: fileName * @Date: 2019-02-13 15:21 * @return: java.lang.String * @throws: */ public static String generateKey(String fileName) { //对象名称格式:yyyymm.name.6位随机字符.ext return new StringBuilder(DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS")) .append(".").append(Utility.getRandomStrByNum(6)) .append(".").append(FilenameUtils.getExtension(fileName)) .toString(); } public static String getHttpsAddress(String url){ return url.replaceAll("http://"+ossProerties.getBucket(),ossProerties.getSslNmae()); } /** * @Title: upload * @Description: 上传方法 * @Author: zte * @param: key 对象名称 * @param: file待上传文件 * @Date: 2019-02-13 15:35 * @return: java.lang.String * @throws: */ public static String upload(String key,File file) { if(file == null || !file.exists()){ log.error("阿里云上传文件失败【"+file+"】不存在"); return null; } log.info("阿里云上传文件开始:【"+file+"】"); OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret()); try { ossClient.putObject(ossProerties.getBucketName(),key,file); //设置url过期时间 Date expirationDate = DateUtils.addYears(new Date(), ossProerties.getExpiration()); String url = ossClient.generatePresignedUrl(ossProerties.getBucketName(), key, expirationDate).toString(); log.info("阿里云上传文件结束:【"+file+"】=>【"+url+"】"); return getHttpsAddress(url); }catch(Exception e) { log.error("阿里云上传文件异常【"+file+"】",e); }finally { ossClient.shutdown(); } return null; } /** * @Title: upload * @Description: 上传方法 * @Author: zte * @param: key 对象名称 * @param: file待上传文件 * @Date: 2019-02-13 15:35 * @return: java.lang.String * @throws: */ public static String upload(String key,byte[] bytes) { if(bytes == null || StringUtils.isBlank(key)){ log.error("阿里云上传文件不存在:【"+key+"】"); return null; } log.info("阿里云上传文件开始:【"+key+"】"); OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret()); try { ossClient.putObject(ossProerties.getBucketName(),key, new ByteArrayInputStream(bytes)); //设置url过期时间 Date expirationDate = DateUtils.addYears(new Date(), 100); String url = ossClient.generatePresignedUrl(ossProerties.getBucketName(), key, expirationDate).toString(); log.info("阿里云上传文件结束:【"+key+"】=>【"+url+"】"); return getHttpsAddress(url); }catch(Exception e) { log.error("阿里云上传文件异常:【"+key+"】",e); }finally { ossClient.shutdown(); } return null; } /** * @Title: uploadWithObjectName * @Description: 上传方法,返回对象名称和 url * @Author: zte * @param: file待上传文件 * @Date: 2019-02-13 15:35 * @return: java.lang.Map<String,String> * @throws: */ public static Map<String,String> uploadWithObjectName(File file) { if(file == null || !file.exists()){ log.error("阿里云上传文件失败【"+file+"】不存在"); return null; } Map<String,String> map = new HashMap<>(); log.info("阿里云上传文件开始:【"+file+"】"); OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret()); try { String key = generateKey(file.getName()); ossClient.putObject(ossProerties.getBucketName(),key, new FileInputStream(file)); //设置url过期时间 Date expirationDate = DateUtils.addYears(new Date(), ossProerties.getExpiration()); String url = ossClient.generatePresignedUrl(ossProerties.getBucketName(), key, expirationDate).toString(); log.info("阿里云上传文件结束:【"+file+"】=>【"+url+"】"); map.put("objectName",key); map.put("url",url); return map; }catch(Exception e) { log.error("阿里云上传文件异常【"+file+"】",e); }finally { ossClient.shutdown(); } return null; } /** * @Title: delete * @Description: 删除方法 * @Author: zte * @param: url 待删除对象url * @Date: 2019-02-13 15:54 * @throws: */ public static void delete(String url) { if(StringUtils.isBlank(url)){ log.error("阿里云删除文件失败,对象url为空"); return; } log.info("阿里云删除文件开始:【"+url+"】"); if(url.contains(ossProerties.getBucket())){ //根据url获取对象名称 url = getObjectNameByUrl(url); } OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret()); try { // 删除文件 ossClient.deleteObject(ossProerties.getBucketName(), url); log.info("阿里云删除文件结束:【"+url+"】"); }catch(Exception e) { log.error("阿里云删除文件异常【"+url+"】",e); }finally { ossClient.shutdown(); } } /** * @Title: download * @Description: 下载文件到本地文件 * @Author: zte * @param: url 待下载对象url * @param: filePath 下载到本地文件 * @Date: 2019-02-13 15:56 * @return: java.io.File * @throws: */ public static File download2File(String url, String filePath) { log.info("阿里云下载文件开始:【"+url+"】"); if(url.contains(ossProerties.getBucket())){ //根据url获取对象名称 url = getObjectNameByUrl(url); } OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret()); try { File file = new File(filePath); // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。 ossClient.getObject(new GetObjectRequest(ossProerties.getBucketName(), url),file); log.info("阿里云下载文件结束:【"+url+"】"); return file; }catch(Exception e) { log.error("阿里云下载文件异常【"+url+"】",e); }finally { ossClient.shutdown(); } return null; } /** * @Title: download * @Description: 通过流下载文件 * @Author: zte * @param: url 待下载对象url * @param: filePath 下载到本地文件 * @Date: 2019-02-13 15:56 * @return: java.io.File * @throws: */ public static void download2FileByStream(String url, String fileName, HttpServletResponse response) { BufferedInputStream inputStream = null; OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret()); try( BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());){ // 配置文件下载 response.setHeader("content-type", "application/octet-stream"); response.setContentType("application/octet-stream"); if(url.contains(ossProerties.getBucket())){ //根据url获取对象名称 url = getObjectNameByUrl(url); } // 下载文件能正常显示中文 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(StringUtils.isBlank(fileName) ? url : fileName, "UTF-8")); log.info("阿里云下载文件开始:【"+url+"】"); // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。 OSSObject ossObject = ossClient.getObject(ossProerties.getBucketName(), url); inputStream = new BufferedInputStream(ossObject.getObjectContent()); byte[] buff = new byte[2048]; int bytesRead; while (-1 != (bytesRead = inputStream.read(buff, 0, buff.length))){ outputStream.write(buff, 0, bytesRead); } outputStream.flush(); } catch (Exception e) { log.error("下载异常!", e); }finally { log.info("阿里云下载文件结束:【"+url+"】"); ossClient.shutdown(); if(inputStream != null){ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * @Title: download * @Description: 下载文件到指定目录,文件名称为阿里云文件对象名称 * @Author: zte * @param: url 待下载对象url * @param: dir 下载到本地目录 * @Date: 2019-02-13 15:56 * @return: java.io.File * @throws: */ public static File download2Dir(String url, String dir) { log.info("阿里云下载文件开始:【"+url+"】"); if(url.contains(ossProerties.getBucket())){ //根据url获取对象名称 url = getObjectNameByUrl(url); } OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret()); try { File file = new File(dir+File.separator+url); // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。 ossClient.getObject(new GetObjectRequest(ossProerties.getBucketName(), url),file); log.info("阿里云下载文件结束:【"+url+"】"); return file; }catch(Exception e) { log.error("阿里云下载文件异常【"+url+"】",e); }finally { ossClient.shutdown(); } return null; } /* * @Title: getObjectNameByUrl * @Description: 通过url获取对象名称 * @Author: lxt * @param: url * @Date: 2019-02-13 16:20 * @return: java.lang.String * @throws: */ public static String getObjectNameByUrl(String url){ if(StringUtils.isBlank(url)){ return null; } return url.substring(url.indexOf(ossProerties.getBucket())+ossProerties.getBucket().length()+1,url.indexOf("?")); } /** * @author: zte * @description: 重载方法,根据file生成文件名称并且上传文件到阿里云 * @date: 2019/9/21 10:56 * @param file : MultipartFile文件 * @see #upload(String,byte[]) * @return 数据库中要存入的路径 */ public static String upload(MultipartFile file) throws IOException { if (file == null || Strings.isEmpty(file.getOriginalFilename())){ return null; } return upload(generateKey(file.getOriginalFilename()), file.getBytes()); } /** * 调用浏览器下载 * @param url * @param response */ public static void download2FileByStream(String url,HttpServletResponse response,String name) { File file = new File(url); String fileName=file.getName(); fileName= StringUtils.substringBefore(fileName,"?"); String fileLast=StringUtils.substringAfterLast(fileName,"."); fileName=name+"."+fileLast; BufferedInputStream inputStream = null; OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret()); try( BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());){ // 配置文件下载 response.setHeader("content-type", "application/octet-stream"); response.setContentType("application/octet-stream"); if(url.contains(ossProerties.getBucket())){ //根据url获取对象名称 url = getObjectNameByUrl(url); } // 下载文件能正常显示中文 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(StringUtils.isBlank(fileName) ? url : fileName, "UTF-8")); log.info("阿里云下载文件开始:【"+url+"】"); // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。 OSSObject ossObject = ossClient.getObject(ossProerties.getBucketName(), url); inputStream = new BufferedInputStream(ossObject.getObjectContent()); byte[] buff = new byte[2048]; int bytesRead; while (-1 != (bytesRead = inputStream.read(buff, 0, buff.length))){ outputStream.write(buff, 0, bytesRead); } outputStream.flush(); } catch (Exception e) { log.error("下载异常!", e); }finally { log.info("阿里云下载文件结束:【"+url+"】"); ossClient.shutdown(); if(inputStream != null){ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }}
5. controller 调用样例
我这里使用的是我自己项目封装的 AjaxResult工具类,大家可以使用Map,通过这个方法呢,我们就可以使用oss将图片保存,并且返回前端图片的保存地址(可以访问)。
/** * 上传 * @param fileupload * @return */ @PostMapping("uploadImg") @ResponseBody public AjaxResult uploadImg(MultipartFile fileupload){ if(fileupload != null){ String path = OssFileUtils.uploadSingleFile(fileupload); return AjaxResult.success(path); }else { return AjaxResult.error(); } }到此这篇关于springboot整合阿里云oss上传的方法示例的文章就介绍到这了,更多相关springboot整合阿里云oss上传内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
今天来整合一下SpringBoot和阿里云OSS对象存储服务。一、配置OSS服务先在阿里云开通对象存储服务,拿到AccessKeyId、AccessKeySec
Thinkphp3.2整合阿里云OSS图片上传实例,图片上传至OSS可减少服务器压力,节省宽带,安全又稳定,阿里云OSS对于做负载均衡非常方便,不用传到各个服务
本文实例讲述了java实现上传文件到oss(阿里云)功能。分享给大家供大家参考,具体如下:做这个功能之前我们需要导入阿里云OSS官方提供的工具包aliyun-s
护卫神云备份(阿里云版)是一款一套为方便广大用户管理阿里云OSS上的文件,如上传、下载、删除等操作,易用性很强,自主开发,完全免费,用于管理阿里云OSS上的文件
网站一般都会有上传功能,而对象存储服务oss是一个很好的选择。可以快速的搭建起自己的上传文件功能。该文章以使用阿里云的OSS功能为例,记录如何在客户端使用阿里云