springboot整合阿里云oss上传的方法示例

时间:2021-05-19

OSS申请和配置

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邮箱联系删除。

相关文章