SpringBoot整合阿里云OSS上传文件

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

一、需求分析

文件上传是一个非常常见的功能,就是通过IO流将文件写到另外一个地方,这个地方可以是项目下的某个文件夹里,或者是本地电脑某个盘下面,还可以是云服务OSS里面,这里就是我要讲到的OSS,我写的是基于阿里云的。

二:环境搭建

我这里是用的Springboot.Thymeleaf插件,为了在html页面实现文件上传功能。

1、首先开通阿里云OSS存储,这里不多说了。

2、创建一个Bucket

这个bucket名称是等下参数里面要用到的。区域可以选择你那边的区域。

3、创建好之后返回刚才的页面,点击Access Key,来获取accessKeyId、accessKeySecret这两个参数

4、Maven依赖(Thymeleaf、OSS)

  1. <!-- 阿里云OSS-->
  2. <dependency>
  3. <groupId>com.aliyun.oss</groupId>
  4. <artifactId>aliyun-sdk-oss</artifactId>
  5. <version>2.4.0</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>commons-fileupload</groupId>
  9. <artifactId>commons-fileupload</artifactId>
  10. <version>1.3.1</version>
  11. </dependency>

5、新建一个UpLoadController.java

  1. **
  2. * @descibe oss
  3. */
  4. @Controller
  5. public class UpLoadController {
  6. private static final String TO_PATH = "upload";
  7. private static final String RETURN_PATH = "success";
  8. @Autowired
  9. private AliyunOSSUtil aliyunOSSUtil;
  10. @RequestMapping("/toUpLoadFile")
  11. public String toUpLoadFile() {
  12. return TO_PATH;
  13. }
  14. /** * 文件上传 */
  15. @RequestMapping(value = "/uploadFile")
  16. public String uploadBlog(@RequestParam("file") MultipartFile file) {
  17. String filename = file.getOriginalFilename();
  18. System.out.println(filename + "==filename");
  19. try {
  20. if (file != null) {
  21. if (!"".equals(filename.trim())) {
  22. File newFile = new File(filename);
  23. FileOutputStream os = new FileOutputStream(newFile);
  24. os.write(file.getBytes());
  25. os.close();
  26. file.transferTo(newFile);
  27. // 上传到OSS
  28. String uploadUrl = aliyunOSSUtil.upLoad(newFile);
  29. }
  30. }
  31. } catch (Exception ex) {
  32. ex.printStackTrace();
  33. }
  34. return RETURN_PATH;
  35. }
  36. }

6、新建AliyunOSSUtil.java

  1. /** * @descibe oss */
  2. @Component
  3. public class AliyunOSSUtil {
  4. private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);
  5. /** * 上传文件 */
  6. public String upLoad(File file) {
  7. logger.info("------OSS文件上传开始--------" + file.getName());
  8. String endpoint = "你的endpoint ";
  9. //这里endpoint 在你的bucket列表->点击你的bucket->点击概览中间就有,下面有截图
  10. System.out.println("获取到的Point为:" + endpoint);
  11. String accessKeyId = "你的accessKeyId "; //accessKeyId 、accessKeySecret 上面有说到哪里获取
  12. String accessKeySecret = "你的accessKeySecret ";
  13. String bucketName = "你的bucketName "; //刚才新建的bucket名称
  14. String fileHost = "你的fileHost "; //在刚才新建的bucket下面新建一个目录,这就是那个目录的名称
  15. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  16. String dateStr = format.format(new Date());
  17. // 判断文件
  18. if (file == null) {
  19. return null;
  20. }
  21. OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  22. try {
  23. // 判断容器是否存在,不存在就创建
  24. if (!client.doesBucketExist(bucketName)) {
  25. client.createBucket(bucketName);
  26. CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
  27. createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
  28. client.createBucket(createBucketRequest);
  29. }
  30. // 设置文件路径和名称
  31. String fileUrl = fileHost + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName());
  32. // 上传文件
  33. PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, fileUrl, file));
  34. // 设置权限(公开读)
  35. client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
  36. if (result != null) {
  37. logger.info("------OSS文件上传成功------" + "https://makeromance.oss-cn-hangzhou.aliyuncs.com/" + fileUrl);
  38. }
  39. } catch (OSSException oe) {
  40. logger.error(oe.getMessage());
  41. } catch (ClientException ce) {
  42. logger.error(ce.getErrorMessage());
  43. } finally {
  44. if (client != null) {
  45. client.shutdown();
  46. }
  47. }
  48. return null;
  49. }
  50. }

获取endpoint:

7、新建upload.html:

  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>【基于OSS的上传文件页面】</title>
  6. <style type="text/css"> * { margin: 0; padding: 0; } #group { position: absolute; left: 580px; } #submit { position: absolute; top: 140px; left: 580px; } </style>
  7. </head>
  8. <body>
  9. <div align="center">
  10. <h2 style="color:orangered;">基于OSS的上传文件页面</h2>
  11. </div>
  12. <br/>
  13. <form action="/uploadFile" enctype="multipart/form-data" method="post">
  14. <div class="form-group" id="group">
  15. <label for="exampleInputFile">File input</label>
  16. <input type="file" id="exampleInputFile" name="file">
  17. </div>
  18. <button type="submit" class="btn btn-default" id="submit">上传</button>
  19. </form>
  20. </body>
  21. </html>

success.html:

  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>【文件上传成功页面】</title>
  6. </head>
  7. <body>
  8. <div align="center">
  9. <h5>上传成功</h5>
  10. <img src="https://makeromance.oss-cn-hangzhou.aliyuncs.com/langmanji/2020-05-27/3c7a040df2ad4f6ca5f6da47373c8773-xiazaierweima.jpg"/>
  11. </div>
  12. </body>
  13. </html>

三、运行项目

选择一个文件点击上传:

提示上传成功,我们看下控制台:

输出的是我们文件上传的路径,然后我们看下我们阿里云OSS存储里面有没有数据:

发现已经有了,这就是一个SpringBoot基于阿里云OSS上传文件的例子。

相关文章