SpringBoot阿里云OSS文件上传功能代码实现

1. 阿里云申请OSS库访问AccessKey ID和AccessKey Secret

2. 配置Maven依赖项

  <dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
  </dependency>

3. 在项目xml配置文件中配置aliyun-oss的属性

  alioss:
    endpoint: 你的 endpoint
    access-key-id: 你的 AccessKey ID
    access-key-secret: 你的 AccessKey Secret
    bucket-name: 你的 bucket-name

4. 创建xml配置文件的属性映射文件,用于获取aliyun-oss的参数

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

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

}

5. 创建主要逻辑代码(官方配置)

@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();
    }
}

6. 创建oss-config配置文件,用于生成AliOssUtil类,交由IOC容器管理

/**
 * 配置类,用于创建阿里OSS until对象
 */
@Configuration
@Slf4j
public class OssConfiguration {

    @Bean // 交给ioc容器管理
    @ConditionalOnMissingBean // 当IOC容器中没有这个bean的时候,才开始创建
    public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties){
        log.info("开始创建阿里云文件上传工具类对象:{}",aliOssProperties);
        return new AliOssUtil(aliOssProperties.getEndpoint(),aliOssProperties.getAccessKeyId(),
                aliOssProperties.getAccessKeySecret(),aliOssProperties.getBucketName());
    }
    
}

 

7. 注入OssConfiguration对象,开始使用upload方法上传文件。

 

posted @ 2023-12-19 12:06  梁哲  阅读(141)  评论(0)    收藏  举报