专栏名称: 武哥聊编程
这里有技术,有段子,有生活,也有资源,要不然怎么叫 “私房菜” 呢?
目录
相关文章推荐
偶俚张家港  ·  张家港第一波!开了!开了!🤩 ·  昨天  
偶俚张家港  ·  张家港第一波!开了!开了!🤩 ·  昨天  
甘肃省教育厅  ·  超500000000人次! ·  昨天  
昆明警方发布  ·  接待游客1464.37万人次 ·  2 天前  
昆明警方发布  ·  接待游客1464.37万人次 ·  2 天前  
掌上铜山  ·  来方特,邂逅甜蜜情人节~ ·  2 天前  
51好读  ›  专栏  ›  武哥聊编程

SpringBoot整合阿里云OSS文件上传、下载、查看、删除

武哥聊编程  · 公众号  ·  · 2020-04-09 08:51

正文

作者:最后的轻语_dd43

链接:https://www.jianshu.com/p/978e206ab8fd

该项目源码地址:https://github.com/ggb2312/JavaNotes/tree/master/springboot-integration-examples (其中包含SpringBoot和其他常用技术的整合,配套源码以及笔记。基于最新的 SpringBoot2.1+,欢迎各位 Star)

1. 开发前准备

1.1 前置知识

  • java基础

  • SpringBoot简单基础知识

1.2 环境参数

  • 开发工具:IDEA

  • 基础环境:Maven+JDK8

  • 所用技术:SpringBoot、lombok、阿里云OSS存储服务

  • SpringBoot版本:2.1.4

1.3 涉及知识点

  • OSS简介,以及阿里云OSS控制台快速入门使用

  • SpringBoot 整合 阿里云OSS 存储服务,进行文件上传、下载、查看、删除

  • 阿里云OSS文档介绍,以及快速入门使用

  • lombok入门使用以及IDEA lombok插件安装

  • SpringMVC与AJAX前后端分离交互

  • AJAX文件异步上传

2. 使用阿里云OSS

对象存储OSS的多重冗余架构设计,为数据持久存储提供可靠保障。

2.1 创建Bucket

使用OSS,首先需要创建Bucket,Bucket翻译成中文是水桶的意思,把存储的图片资源看做是水,想要盛水必须得\ 有桶。\ 进入控制台,https://oss.console.aliyun.com/overview

新建Bucket

新建 Bucket

创建完成后,在左侧可以看到已经创建好的Bucket:

Bucket

选择Bucket后,即可看到对应的信息,如:url、消耗流量等

Bucket相关信息

2.2 管理文件

可以通过在线的方式进行管理文件

管理文件

2.3 阿里云OSS文档

阿里云OSS文档

阿里云OSS文档

右侧的开发指南说的更加详细

开发指南

阿里云虽然提供了完整的文档,但是做一个完整的前后端交互的文件上传、下载、查看、删除等操作,对于小白来说还是有点难度的,所以我把自己学习OSS的步骤以及代码分享了出来,共有需要的人使用。

3. 项目初始化

3.1 创建SpringBoot项目

在Idea中File------>New------>Project

创建SpringBoot项目 步骤一

创建SpringBoot项目 步骤二

创建SpringBoot项目 步骤三

创建SpringBoot项目 步骤四

3.2 Maven依赖

导入Maven相关依赖

  1. com.aliyun.oss

  2. aliyun-sdk-oss

  3. 2.8.3


  4. org.projectlombok

  5. lombok

  6. 1.18.4

  7. provided


  8. joda-time

  9. joda-time

  10. 2.9.9


  11. org.apache.commons

  12. commons-lang3

  13. 3.8.1

3.3 安装lombok插件

因为项目中使用了lombok的 @Data 注解,当然你也可以自己写get、set等方法。\ File------>settings------>Plugins

安装lombok插件

安装lombok插件

然后restart IDEA即可。

4. 后端服务编写

项目结构

4.1 阿里云OSS配置

在resource下新建一个application-oss.properties

  1. aliyun.endpoint=oss-cn-shanghai.aliyuncs.com

  2. aliyun.accessKeyId=你的accessKeyId

  3. aliyun .accessKeySecret=你的accessKeySecret

  4. aliyun.bucketName=gaojun-testbucket

  5. aliyun.urlPrefix=http://gaojun-testbucket.oss-cn-shanghai.aliyuncs.com/

  6. spring.servlet.multipart.max-file-size=100MB

  7. spring.servlet.multipart.max-request-size=1000MB

endpoint、bucketName、urlPrefix在OSS主面板就可以看到

bucketName、endpoint与urlPrefix

accessKeyId、accessKeySecret需要在accesskeys里面查看

accesskeys与accessKeySecret

在java的包下新建一个config包,创建一个AliyunConfig.java

  1. package com.example.ossdemo.config;


  2. import com.aliyun.oss.OSS;

  3. import com.aliyun.oss. OSSClient;

  4. import lombok.Data;

  5. import org.springframework.boot.context.properties.ConfigurationProperties;

  6. import org.springframework.context.annotation.Bean;

  7. import org.springframework.context.annotation.Configuration;

  8. import org.springframework.context.annotation.PropertySource;

  9. /**

  10. * @desc

  11. *

  12. * @author lastwhisper

  13. * @email [email protected]

  14. */

  15. @Configuration

  16. @PropertySource(value = {"classpath:application-oss.properties"})

  17. @ConfigurationProperties(prefix = "aliyun")

  18. @Data

  19. public class AliyunConfig {

  20. private String endpoint;

  21. private String accessKeyId;

  22. private String accessKeySecret;

  23. private String bucketName;

  24. private String urlPrefix;


  25. @Bean

  26. public OSS oSSClient() {

  27. return new OSSClient(endpoint, accessKeyId, accessKeySecret);

  28. }

  29. }

4.2 后端业务

4.2.1 vo

该实体类用于后台返回给前台。

  1. package com.example.ossdemo.vo;


  2. import lombok.Data;


  3. /**

  4. * @author lastwhisper

  5. * @desc 用于前后端交互的返回值

  6. * @email [email protected]

  7. */

  8. @Data

  9. public class FileUploadResult {

  10. // 文件唯一标识

  11. private String uid;

  12. // 文件名

  13. private String name;

  14. // 状态有:uploading done error removed

  15. private String status;

  16. // 服务端响应内容,如:'{"status": "success"}'

  17. private String response;

  18. }

4.2.2 service

在service使用ossClient操作阿里云OSS,进行上传、下载、删除、查看所有文件等操作,同时可以将图片的url进行入库操作。

  1. package com.example.ossdemo.service;


  2. import com.aliyun.oss.OSS;

  3. import com.aliyun.oss.model.*;

  4. import com.example.ossdemo.config.AliyunConfig;

  5. import com.example.ossdemo.vo.FileUploadResult ;

  6. import org.apache.commons.lang3.RandomUtils;

  7. import org.apache.commons.lang3.StringUtils;

  8. import org.joda.time.DateTime;

  9. import org.springframework.beans.factory.annotation.Autowired;

  10. import org.springframework.stereotype.Service;

  11. import org.springframework.web.multipart.MultipartFile;


  12. import java.io.*;

  13. import java.util.List;


  14. /**

  15. * @author lastwhisper

  16. * @desc

  17. * @email [email protected]

  18. */

  19. @Service

  20. public class FileUploadService {

  21. // 允许上传的格式

  22. private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",

  23. ".jpeg", ".gif", ".png"};

  24. @Autowired

  25. private OSS ossClient;

  26. @Autowired

  27. private AliyunConfig aliyunConfig;


  28. /**

  29. * @author lastwhisper

  30. * @desc 文件上传

  31. * 文档链接 https://help.aliyun.com/document_detail/84781.html?spm=a2c4g.11186623.6.749.11987a7dRYVSzn

  32. * @email [email protected]

  33. */

  34. public FileUploadResult upload(MultipartFile uploadFile) {

  35. // 校验图片格式

  36. boolean isLegal = false;

  37. for (String type : IMAGE_TYPE) {

  38. if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),

  39. type)) {

  40. isLegal = true;

  41. break;

  42. }

  43. }

  44. //封装Result对象,并且将文件的byte数组放置到result对象中

  45. FileUploadResult fileUploadResult = new FileUploadResult();

  46. if (!isLegal) {

  47. fileUploadResult.setStatus("error");

  48. return fileUploadResult;

  49. }

  50. //文件新路径

  51. String fileName = uploadFile.getOriginalFilename();

  52. String filePath = getFilePath(fileName);

  53. // 上传到阿里云

  54. try {

  55. ossClient .putObject(aliyunConfig.getBucketName(), filePath, new

  56. ByteArrayInputStream(uploadFile.getBytes()));

  57. } catch (Exception e) {

  58. e.printStackTrace();

  59. //上传失败

  60. fileUploadResult.setStatus("error");

  61. return fileUploadResult;

  62. }

  63. fileUploadResult.setStatus("done");

  64. fileUploadResult.setResponse("success");

  65. //this.aliyunConfig.getUrlPrefix() + filePath 文件路径需要保存到数据库

  66. fileUploadResult.setName(this.aliyunConfig.getUrlPrefix () + filePath);

  67. fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));

  68. return fileUploadResult;

  69. }


  70. /**

  71. * @author lastwhisper

  72. * @desc 生成路径以及文件名 例如://images/2019/04/28/15564277465972939.jpg

  73. * @email [email protected]

  74. */

  75. private String getFilePath(String sourceFileName) {

  76. DateTime dateTime = new DateTime();

  77. return "images/" + dateTime.toString("yyyy")

  78. + "/" + dateTime.toString("MM") + "/"

  79. + dateTime.toString("dd") + "/" + System.currentTimeMillis() +

  80. RandomUtils.nextInt(100, 9999) + "." +

  81. StringUtils.substringAfterLast(sourceFileName, ".");

  82. }


  83. /**

  84. * @author lastwhisper

  85. * @desc 查看文件列表

  86. * 文档链接 https://help.aliyun.com/document_detail/84841.html?spm=a2c4g.11186623.2.13.3ad5b5ddqxWWRu#concept-84841-zh

  87. * @email [email protected]

  88. */

  89. public List <OSSObjectSummary> list() {

  90. // 设置最大个数。

  91. final int maxKeys = 200;

  92. // 列举文件。

  93. ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(aliyunConfig.getBucketName()).withMaxKeys(maxKeys));

  94. List<OSSObjectSummary> sums = objectListing.getObjectSummaries();

  95. return sums;

  96. }


  97. /**

  98. * @author lastwhisper

  99. * @desc 删除文件

  100. * 文档链接 https://help.aliyun.com/document_detail/84842.html?spm=a2c4g.11186623.6.770.4f9474b4UYlCtr

  101. * @email [email protected]

  102. */

  103. public FileUploadResult delete(String objectName) {

  104. // 根据BucketName,objectName删除文件

  105. ossClient.deleteObject(aliyunConfig.getBucketName(), objectName);

  106. FileUploadResult fileUploadResult = new FileUploadResult();

  107. fileUploadResult.setName(objectName);

  108. fileUploadResult.setStatus("removed");

  109. fileUploadResult.setResponse("success");

  110. return fileUploadResult;

  111. }


  112. /**

  113. * @author lastwhisper

  114. * @desc 下载文件

  115. * 文档链接 https://help.aliyun.com/document_detail/84823.html?spm=a2c4g.11186623.2.7.37836e84ZIuZaC#concept-84823-zh

  116. * @email [email protected]

  117. */

  118. public void exportOssFile(OutputStream os, String objectName) throws IOException {

  119. // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。

  120. OSSObject ossObject = ossClient.getObject(aliyunConfig.getBucketName(), objectName);

  121. // 读取文件内容。

  122. BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());

  123. BufferedOutputStream out = new BufferedOutputStream(os);

  124. byte[] buffer = new byte [1024];

  125. int lenght = 0;

  126. while ((lenght = in.read(buffer)) != -1) {

  127. out.write(buffer, 0, lenght);

  128. }

  129. if (out != null) {

  130. out.flush();

  131. out.close();

  132. }

  133. if (in != null) {

  134. in.close();

  135. }

  136. }

  137. }

4.2.3 controller

controller进行接收用户请求

  1. package com.example.ossdemo.controller;


  2. import com.aliyun.oss.model.OSSObjectSummary;

  3. import com.example.ossdemo.service.FileUploadService;

  4. import com.example.ossdemo.vo.FileUploadResult;

  5. import org.springframework.beans.factory.annotation.Autowired;

  6. import org.springframework.http.HttpHeaders ;

  7. import org.springframework.http.HttpStatus;

  8. import org.springframework.http.MediaType;

  9. import org.springframework.http.ResponseEntity;

  10. import org.springframework.stereotype.Controller;

  11. import org.springframework.web.bind.annotation.RequestMapping;

  12. import org.springframework.web.bind.annotation.RequestParam;

  13. import org.springframework.web.bind.annotation.ResponseBody;

  14. import org.springframework.web.multipart.MultipartFile;


  15. import javax.servlet.http.HttpServletResponse;

  16. import java.io.IOException;

  17. import java.io.InputStream;

  18. import java.net.URLEncoder;

  19. import java.util.List;


  20. /**

  21. * @author lastwhisper

  22. * @desc

  23. * @email [email protected]

  24. */

  25. @Controller

  26. public class FileUploadController {

  27. @Autowired

  28. private FileUploadService fileUploadService;


  29. /**

  30. * @author lastwhisper

  31. * @desc 文件上传到oss

  32. * @return FileUploadResult

  33. * @Param uploadFile

  34. */

  35. @RequestMapping("file/upload")

  36. @ResponseBody

  37. public FileUploadResult upload(@RequestParam("file") MultipartFile uploadFile)

  38. throws Exception {

  39. return this.fileUploadService.upload(uploadFile);

  40. }


  41. /**

  42. * @return FileUploadResult

  43. * @desc 根据文件名删除oss上的文件

  44. * http://localhost:8080/file/delete?fileName=images/2019/04/28/1556429167175766.jpg

  45. * @author lastwhisper

  46. * @Param objectName

  47. */

  48. @RequestMapping("file/delete")

  49. @ResponseBody

  50. public FileUploadResult delete(@RequestParam("fileName") String objectName)

  51. throws Exception {

  52. return this.fileUploadService.delete(objectName);

  53. }


  54. /**

  55. * @author lastwhisper

  56. * @desc 查询oss上的所有文件

  57. * http://localhost:8080/file/list

  58. * @return List

  59. * @Param

  60. */

  61. @RequestMapping("file/list")

  62. @ResponseBody

  63. public List<OSSObjectSummary> list()

  64. throws Exception {

  65. return this.fileUploadService.list();

  66. }


  67. /**

  68. * @author lastwhisper

  69. * @desc 根据文件名下载oss上的文件

  70. * @return

  71. * @Param objectName

  72. */

  73. @RequestMapping("file/download")

  74. @ResponseBody

  75. public void download(@RequestParam("fileName") String objectName, HttpServletResponse response) throws IOException {

  76. //通知浏览器以附件形式下载

  77. response.setHeader("Content-Disposition",

  78. "attachment;filename=" + new String(objectName.getBytes(), "ISO-8859-1"));

  79. this.fileUploadService.exportOssFile(response.getOutputStream(),objectName);

  80. }

  81. }

5. 前端页面编写与测试

5.1 文件上传页面

使用ajax异步文件上传到后端对接的OSS上。

  1. lang="en">

  2. charset="UTF-8">







请到「今天看啥」查看全文