SpringBoot整合oss实现文件的上传,查看,删除,下载

x33g5p2x  于2021-12-23 转载在 Spring  
字(8.3k)|赞(0)|评价(0)|浏览(627)

springboot整合oss实现文件的上传,查看,删除,下载

1.什么是对象存储 OSS?

答:阿里云对象存储服务(Object Storage Service,简称 OSS),是阿里云提供的海量、安全、低成本、高可靠的云存储服务。其数据设计持久性不低于 99.9999999999%(12 个 9),服务设计可用性(或业务连续性)不低于 99.995%。

OSS 具有与平台无关的 RESTful API 接口,您可以在任何应用、任何时间、任何地点存储和访问任意类型的数据。

您可以使用阿里云提供的 API、SDK 接口或者 OSS 迁移工具轻松地将海量数据移入或移出阿里云 OSS。数据存储到阿里云 OSS 以后,您可以选择标准存储(Standard)作为移动应用、大型网站、图片分享或热点音视频的主要存储方式,也可以选择成本更低、存储期限更长的低频访问存储(Infrequent Access)和归档存储(Archive)作为不经常访问数据的存储方式。

有关oss更多,更详细的介绍请参考阿里云oss对象储存官方文档地址

2.登录阿里云,进入到控制台

3.创建Bucket

点击确定,这样我们就建好了。

下面我们来开始写代码?

新建一个spring boot项目

导入如下依赖

pom.xml

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-test</artifactId>
  8. <scope>test</scope>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-devtools</artifactId>
  13. <optional>true</optional>
  14. </dependency>
  15. <dependency>
  16. <groupId>com.aliyun.oss</groupId>
  17. <artifactId>aliyun-sdk-oss</artifactId>
  18. <version>2.8.3</version>
  19. </dependency>
  20. <dependency>
  21. <groupId>org.projectlombok</groupId>
  22. <artifactId>lombok</artifactId>
  23. <version>1.18.4</version>
  24. <scope>provided</scope>
  25. </dependency>
  26. <dependency>
  27. <groupId>joda-time</groupId>
  28. <artifactId>joda-time</artifactId>
  29. <version>2.9.9</version>
  30. </dependency>
  31. <dependency>
  32. <groupId>org.apache.commons</groupId>
  33. <artifactId>commons-lang3</artifactId>
  34. <version>3.8.1</version>
  35. </dependency>

application.properties配置文件

accessKeyId、accessKeySecret需要在accesskeys里面查看

编写一个配置文件AliyunConfig.class

  1. package com.tuanzi.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. /** * @desc */
  10. @Configuration
  11. @PropertySource(value = {"classpath:application.properties"})
  12. @ConfigurationProperties(prefix = "aliyun")
  13. @Data
  14. public class AliyunConfig {
  15. private String endpoint;
  16. private String accessKeyId;
  17. private String accessKeySecret;
  18. private String bucketName;
  19. private String urlPrefix;
  20. @Bean
  21. public OSS oSSClient() {
  22. return new OSSClient(endpoint, accessKeyId, accessKeySecret);
  23. }
  24. }

controller类

  1. package com.tuanzi.controller;
  2. import com.tuanzi.service.FileUploadService;
  3. import com.tuanzi.vo.FileUploadResult;
  4. import com.aliyun.oss.model.OSSObjectSummary;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RequestParam;
  9. import org.springframework.web.bind.annotation.ResponseBody;
  10. import org.springframework.web.multipart.MultipartFile;
  11. import javax.servlet.http.HttpServletResponse;
  12. import java.io.IOException;
  13. import java.util.List;
  14. /** * @desc */
  15. @Controller
  16. public class FileUploadController {
  17. @Autowired
  18. private FileUploadService fileUploadService;
  19. /** * @desc 文件上传到oss * @return FileUploadResult * @Param uploadFile */
  20. @RequestMapping("file/upload")
  21. @ResponseBody
  22. public FileUploadResult upload(@RequestParam("file") MultipartFile uploadFile)
  23. throws Exception {
  24. return this.fileUploadService.upload(uploadFile);
  25. }
  26. /** * @return FileUploadResult * @desc 根据文件名删除oss上的文件 * @Param objectName */
  27. @RequestMapping("file/delete")
  28. @ResponseBody
  29. public FileUploadResult delete(@RequestParam("fileName") String objectName)
  30. throws Exception {
  31. return this.fileUploadService.delete(objectName);
  32. }
  33. /** * @desc 查询oss上的所有文件 * @return List<OSSObjectSummary> * @Param */
  34. @RequestMapping("file/list")
  35. @ResponseBody
  36. public List<OSSObjectSummary> list()
  37. throws Exception {
  38. return this.fileUploadService.list();
  39. }
  40. /** * @desc 根据文件名下载oss上的文件 * @return * @Param objectName */
  41. @RequestMapping("file/download")
  42. @ResponseBody
  43. public void download(@RequestParam("fileName") String objectName, HttpServletResponse response) throws IOException {
  44. //通知浏览器以附件形式下载
  45. response.setHeader("Content-Disposition",
  46. "attachment;filename=" + new String(objectName.getBytes(), "ISO-8859-1"));
  47. this.fileUploadService.exportOssFile(response.getOutputStream(),objectName);
  48. }
  49. }

service

  1. package com.tuanzi.service;
  2. import com.tuanzi.config.AliyunConfig;
  3. import com.tuanzi.vo.FileUploadResult;
  4. import com.aliyun.oss.OSS;
  5. import com.aliyun.oss.model.*;
  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. /** * @desc */
  15. @Service
  16. public class FileUploadService {
  17. // 允许上传的格式
  18. private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",
  19. ".jpeg", ".gif", ".png"};
  20. @Autowired
  21. private OSS ossClient;
  22. @Autowired
  23. private AliyunConfig aliyunConfig;
  24. /** * @desc 文件上传 */
  25. public FileUploadResult upload(MultipartFile uploadFile) {
  26. // 校验图片格式
  27. boolean isLegal = false;
  28. for (String type : IMAGE_TYPE) {
  29. if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),
  30. type)) {
  31. isLegal = true;
  32. break;
  33. }
  34. }
  35. //封装Result对象,并且将文件的byte数组放置到result对象中
  36. FileUploadResult fileUploadResult = new FileUploadResult();
  37. if (!isLegal) {
  38. fileUploadResult.setStatus("error");
  39. return fileUploadResult;
  40. }
  41. //文件新路径
  42. String fileName = uploadFile.getOriginalFilename();
  43. String filePath = getFilePath(fileName);
  44. // 上传到阿里云
  45. try {
  46. ossClient.putObject(aliyunConfig.getBucketName(), filePath, new
  47. ByteArrayInputStream(uploadFile.getBytes()));
  48. } catch (Exception e) {
  49. e.printStackTrace();
  50. //上传失败
  51. fileUploadResult.setStatus("error");
  52. return fileUploadResult;
  53. }
  54. fileUploadResult.setStatus("done");
  55. fileUploadResult.setResponse("success");
  56. fileUploadResult.setName(this.aliyunConfig.getUrlPrefix() + filePath);
  57. fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
  58. return fileUploadResult;
  59. }
  60. /** * @desc 生成路径以及文件名 例如://images/2019/08/10/15564277465972939.jpg */
  61. private String getFilePath(String sourceFileName) {
  62. DateTime dateTime = new DateTime();
  63. return "images/" + dateTime.toString("yyyy")
  64. + "/" + dateTime.toString("MM") + "/"
  65. + dateTime.toString("dd") + "/" + System.currentTimeMillis() +
  66. RandomUtils.nextInt(100, 9999) + "." +
  67. StringUtils.substringAfterLast(sourceFileName, ".");
  68. }
  69. /** * @desc 查看文件列表 */
  70. public List<OSSObjectSummary> list() {
  71. // 设置最大个数。
  72. final int maxKeys = 200;
  73. // 列举文件。
  74. ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(aliyunConfig.getBucketName()).withMaxKeys(maxKeys));
  75. List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
  76. return sums;
  77. }
  78. /** * @desc 删除文件 */
  79. public FileUploadResult delete(String objectName) {
  80. // 根据BucketName,objectName删除文件
  81. ossClient.deleteObject(aliyunConfig.getBucketName(), objectName);
  82. FileUploadResult fileUploadResult = new FileUploadResult();
  83. fileUploadResult.setName(objectName);
  84. fileUploadResult.setStatus("removed");
  85. fileUploadResult.setResponse("success");
  86. return fileUploadResult;
  87. }
  88. /** * @desc 下载文件 */
  89. public void exportOssFile(OutputStream os, String objectName) throws IOException {
  90. // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
  91. OSSObject ossObject = ossClient.getObject(aliyunConfig.getBucketName(), objectName);
  92. // 读取文件内容。
  93. BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());
  94. BufferedOutputStream out = new BufferedOutputStream(os);
  95. byte[] buffer = new byte[1024];
  96. int lenght = 0;
  97. while ((lenght = in.read(buffer)) != -1) {
  98. out.write(buffer, 0, lenght);
  99. }
  100. if (out != null) {
  101. out.flush();
  102. out.close();
  103. }
  104. if (in != null) {
  105. in.close();
  106. }
  107. }
  108. }

返回值类

  1. package com.tuanzi.vo;
  2. import lombok.Data;
  3. /** * @desc 返回值 */
  4. @Data
  5. public class FileUploadResult {
  6. // 文件唯一标识
  7. private String uid;
  8. // 文件名
  9. private String name;
  10. // 状态有:uploading done error removed
  11. private String status;
  12. // 服务端响应内容,如:'{"status": "success"}'
  13. private String response;
  14. }

这样就完成了
我们来运行一下项目
看看效果:访问http://localhost:8080/upload.html

我们来上传一个不符合格式的图片,会有提示信息

来上传一个符合的

上传成功后会直接显示出来。我们来看看oss里面是否有我们上传的图片

发现也有
接下来我们来测试一下查询,下载,和删除
访问:http://localhost:8080/manager.html

会看到我们上传的图片
这里简单的写了个例子
下载图片

删除图片

来看看oss里面

也已经删除了!!!

相关文章