Spring boot阿里云OSS文件上传实现

[复制链接]
admin 发表于 2025-9-15 21:23:29 | 显示全部楼层 |阅读模式
Spring boot阿里云OSS文件上传实现

1). 定义OSS相关配置
在sky-server模块
application-dev.yml
  1. sky:
  2.   alioss:
  3.     endpoint: oss-cn-hangzhou.aliyuncs.com
  4.     access-key-id: LTAI5tPeFLzsPPT8gG3LPW64
  5.     access-key-secret: U6k1brOZ8gaOIXv3nXbulGTUzy6Pd7
  6.     bucket-name: sky-take-out
复制代码
application.yml
  1. spring:
  2.   profiles:
  3.     active: dev    #设置环境
  4. sky:
  5.   alioss:
  6.     endpoint: ${sky.alioss.endpoint}
  7.     access-key-id: ${sky.alioss.access-key-id}
  8.     access-key-secret: ${sky.alioss.access-key-secret}
  9.     bucket-name: ${sky.alioss.bucket-name}
复制代码
1.jpg

2). 读取OSS配置
在sky-common模块中,已定义
代码如下:
  1. package com.sky.properties;

  2. import lombok.Data;
  3. import org.springframework.boot.context.properties.ConfigurationProperties;
  4. import org.springframework.stereotype.Component;

  5. @Component
  6. @ConfigurationProperties(prefix = "sky.alioss")
  7. @Data
  8. public class AliOssProperties {

  9.     private String endpoint;
  10.     private String accessKeyId;
  11.     private String accessKeySecret;
  12.     private String bucketName;

  13. }
复制代码
2.jpg

3). 生成OSS工具类对象
在sky-server模块
  1. package com.sky.config;

  2. import com.sky.properties.AliOssProperties;
  3. import com.sky.utils.AliOssUtil;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;

  8. /**
  9. * 配置类,用于创建AliOssUtil对象
  10. */
  11. @Configuration
  12. @Slf4j
  13. public class OssConfiguration {

  14.     @Bean
  15.     @ConditionalOnMissingBean
  16.     public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties){
  17.         log.info("开始创建阿里云文件上传工具类对象:{}",aliOssProperties);
  18.         return new AliOssUtil(aliOssProperties.getEndpoint(),
  19.                 aliOssProperties.getAccessKeyId(),
  20.                 aliOssProperties.getAccessKeySecret(),
  21.                 aliOssProperties.getBucketName());
  22.     }
  23. }
复制代码
1.jpg
其中,AliOssUtil.java已在sky-common模块中定义
  1. package com.sky.utils;

  2. import com.aliyun.oss.ClientException;
  3. import com.aliyun.oss.OSS;
  4. import com.aliyun.oss.OSSClientBuilder;
  5. import com.aliyun.oss.OSSException;
  6. import lombok.AllArgsConstructor;
  7. import lombok.Data;
  8. import lombok.extern.slf4j.Slf4j;
  9. import java.io.ByteArrayInputStream;

  10. @Data
  11. @AllArgsConstructor
  12. @Slf4j
  13. public class AliOssUtil {

  14.     private String endpoint;
  15.     private String accessKeyId;
  16.     private String accessKeySecret;
  17.     private String bucketName;

  18.     /**
  19.      * 文件上传
  20.      *
  21.      * @param bytes
  22.      * @param objectName
  23.      * @return
  24.      */
  25.     public String upload(byte[] bytes, String objectName) {

  26.         // 创建OSSClient实例。
  27.         OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

  28.         try {
  29.             // 创建PutObject请求。
  30.             ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
  31.         } catch (OSSException oe) {
  32.             System.out.println("Caught an OSSException, which means your request made it to OSS, "
  33.                     + "but was rejected with an error response for some reason.");
  34.             System.out.println("Error Message:" + oe.getErrorMessage());
  35.             System.out.println("Error Code:" + oe.getErrorCode());
  36.             System.out.println("Request ID:" + oe.getRequestId());
  37.             System.out.println("Host ID:" + oe.getHostId());
  38.         } catch (ClientException ce) {
  39.             System.out.println("Caught an ClientException, which means the client encountered "
  40.                     + "a serious internal problem while trying to communicate with OSS, "
  41.                     + "such as not being able to access the network.");
  42.             System.out.println("Error Message:" + ce.getMessage());
  43.         } finally {
  44.             if (ossClient != null) {
  45.                 ossClient.shutdown();
  46.             }
  47.         }

  48.         //文件访问路径规则 https://BucketName.Endpoint/ObjectName
  49.         StringBuilder stringBuilder = new StringBuilder("https://");
  50.         stringBuilder
  51.                 .append(bucketName)
  52.                 .append(".")
  53.                 .append(endpoint)
  54.                 .append("/")
  55.                 .append(objectName);

  56.         log.info("文件上传到:{}", stringBuilder.toString());

  57.         return stringBuilder.toString();
  58.     }
  59. }
复制代码
2.jpg

4). 定义文件上传接口
在sky-server模块中定义接口
  1. package com.sky.controller.admin;

  2. import com.sky.constant.MessageConstant;
  3. import com.sky.result.Result;
  4. import com.sky.utils.AliOssUtil;
  5. import io.swagger.annotations.Api;
  6. import io.swagger.annotations.ApiOperation;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.web.bind.annotation.PostMapping;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RestController;
  12. import org.springframework.web.multipart.MultipartFile;
  13. import java.io.IOException;
  14. import java.util.UUID;

  15. /**
  16. * 通用接口
  17. */
  18. @RestController
  19. @RequestMapping("/admin/common")
  20. @Api(tags = "通用接口")
  21. @Slf4j
  22. public class CommonController {

  23.     @Autowired
  24.     private AliOssUtil aliOssUtil;

  25.     /**
  26.      * 文件上传
  27.      * @param file
  28.      * @return
  29.      */
  30.     @PostMapping("/upload")
  31.     @ApiOperation("文件上传")
  32.     public Result<String> upload(MultipartFile file){
  33.         log.info("文件上传:{}",file);

  34.         try {
  35.             //原始文件名
  36.             String originalFilename = file.getOriginalFilename();
  37.             //截取原始文件名的后缀   dfdfdf.png
  38.             String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
  39.             //构造新文件名称
  40.             String objectName = UUID.randomUUID().toString() + extension;

  41.             //文件的请求路径
  42.             String filePath = aliOssUtil.upload(file.getBytes(), objectName);
  43.             return Result.success(filePath);
  44.         } catch (IOException e) {
  45.             log.error("文件上传失败:{}", e);
  46.         }

  47.         return Result.error(MessageConstant.UPLOAD_FAILED);
  48.     }
  49. }
复制代码
3.jpg

网站建设,公众号小程序开发,多商户单商户小程序制作,高端系统定制开发,App软件开发联系我们【手机/微信:17817817816
微信扫码

网站建设,公众号小程序开发,商城小程序,系统定制开发,App软件开发等

粤ICP备2024252464号

在本版发帖
微信扫码
QQ客服返回顶部
快速回复 返回顶部 返回列表