本文最后更新于 2024-07-08,文章内容可能已经过时。

SpringBoot阿里云OSS存储配置

1. 导入依赖

<!--阿里云oss存储-->
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.15.1</version>
</dependency>
    <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

2. 编写配置类

2.1 yml文件配置

spring:
  # 文件上传
  servlet:
    multipart:
      # 单个文件大小
      max-file-size: 200MB
      # 设置总上传的文件大小
      max-request-size: 500MB

aliyun:
  # 阿里云OSS存储
  oss:
    endpoint: oss-cn-guangzhou.aliyuncs.com #外网访问的地域节点
    access-key-id: LTAI5t9WabH9cVp9Gp4sXFP9 #访问阿里云api的秘钥
    access-key-secret: EKiDiDpvAJeohD522Ir4puPWF262Dh #访问阿里云api的秘钥
    bucket-name: forum-file #bucket-name

2.2 阿里云OSS存储属性

/**
 * desc 阿里云OSS存储属性
 * @author GreyPigeon mail:2371849349@qq.com
 * @since 2024-05-05-23:09
 **/

@Component
@ConfigurationProperties(prefix = "aliyun.oss")
@Data
public class AliOssProperties {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

}

2.3 阿里云通用文件上传工具类

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.time.LocalDateTime;

/**
 * desc :阿里云通用文件上传工具类
 * @author GreyPigeon mail:2371849349@qq.com
 * @since 2024-05-05-23:11
 **/
@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    /**
     * 文件上传
     *
     * @param bytes
     * @param objectName
     * @return
     */
    public String upload(byte[] bytes, String objectName) {

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

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

        //文件访问路径规则 https://BucketName.Endpoint/ObjectName
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(objectName)
                ;

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

        return stringBuilder.toString();
    }

    /**
     * @return
     */
    public static String getOssDefaultPath() {
        LocalDateTime now = LocalDateTime.now();
        String url =
                now.getYear() + "/" +
                        now.getMonth() + "/" +
                        now.getDayOfMonth() + "/" +
                        now.getHour() + "/" +
                        now.getMinute() + "/";
        return url;
    }
}

2.4 配置类,用于创建AliOssUtil对象

/**
 * desc :配置类,用于创建AliOssUtil对象
 * @author GreyPigeon mail:2371849349@qq.com
 * @since 2024-05-05-23:13
 **/
@Configuration
@Slf4j
public class OssConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties){
        log.info("开始创建阿里云文件上传工具类对象:{}",aliOssProperties);
        return new AliOssUtil(aliOssProperties.getEndpoint(),
                aliOssProperties.getAccessKeyId(),
                aliOssProperties.getAccessKeySecret(),
                aliOssProperties.getBucketName());
    }
}

2.5 接口测试

/**
 * desc 通用接口
 * @author GreyPigeon mail:2371849349@qq.com
 * @since 2024-05-05-21:18
 **/

@RestController
@RequestMapping("/common")
@Tag(name = "通用接口")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @Operation(summary = "文件上传",description = "文件上传:OSS存储")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传:{}",file);

        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀.png .jpg
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName = AliOssUtil.getOssDefaultPath() + UUID.randomUUID().toString() + extension;

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

        return Result.fail("文件上传失败");
    }
}

参考:https://blog.csdn.net/m0_60817860/article/details/135818446?