SpringBoot集成阿里云OSS上传文件

文章目录

  • 前言
  • 一、准备环境
    • 1、在搜索框搜索 对象存储OSS
    • 2、创建Bucket
    • 3、找到开发相关信息
  • 二、具体代码
    • 1、Maven依赖
    • 2、application.yml配置
    • 3、AliOssProperties配置类
    • 4、AliOssUtil类
  • 三、测试
  • 总结

前言

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

一、准备环境

1、在搜索框搜索 对象存储OSS

SpringBoot集成阿里云OSS上传文件_第1张图片

2、创建Bucket

SpringBoot集成阿里云OSS上传文件_第2张图片

3、找到开发相关信息

SpringBoot集成阿里云OSS上传文件_第3张图片
SpringBoot集成阿里云OSS上传文件_第4张图片
在这里插入图片描述

  • 获取 bucketName ,选择指定的 Bucket 列表,复制名称就行了
    SpringBoot集成阿里云OSS上传文件_第5张图片
  • 获取 endpoint , 点击指定的 Bucket ,地域不同的 Bucket 的 endpoint 是不一样的
    SpringBoot集成阿里云OSS上传文件_第6张图片

二、具体代码

1、Maven依赖

        <dependency>
            <groupId>com.aliyun.ossgroupId>
            <artifactId>aliyun-sdk-ossartifactId>
            <version>3.14.0version>
        dependency>

2、application.yml配置

#阿里云存储文件系统配置
file:
  store:
    ali:
      oss:
        endpoint: xxxxx
        bucket: xxxxx
        accessKey: xxxxx
        secretKey: xxxxx

3、AliOssProperties配置类

package com.central.filesystem.common.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "file.store.ali.oss")
@RefreshScope
public class AliOssProperties {
    private String endpoint;
    private String bucket;
    private String accessKey;
    private String secretKey;
}

4、AliOssUtil类

package com.central.filesystem.common.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.model.CompleteMultipartUploadResult;
import com.aliyun.oss.model.UploadFileRequest;
import com.aliyun.oss.model.UploadFileResult;
import com.central.filesystem.common.config.AliOssProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class AliOssUtil {
    @Autowired
    private AliOssProperties aliOssProperties;

    private static final Logger logger = LoggerFactory.getLogger(AliOssUtil.class);

    private static OSS ossClient;

    public AliOssUtil(AliOssProperties aliOssProperties) {
        this.aliOssProperties = aliOssProperties;
    }

    @PostConstruct
    public void init() {
        try {
            ossClient = new OSSClientBuilder().build(aliOssProperties.getEndpoint(), aliOssProperties.getAccessKey(), aliOssProperties.getSecretKey());
        } catch (Exception e) {
            logger.error("初始化阿里云配置异常", e.fillInStackTrace());
        }
    }

    public String upload(String uploadFile, String objectFile, Boolean shutdown) {

        //OSS ossClient = new OSSClientBuilder().build(aliOssProperties.getEndpoint(), aliOssProperties.getAccessKey(), aliOssProperties.getSecretKey());
        String location = "";

        try {
            UploadFileRequest uploadFileRequest = new UploadFileRequest(aliOssProperties.getBucket(), objectFile);
            // The local file to upload---it must exist.
            uploadFileRequest.setUploadFile(uploadFile);//文件本地物理路径
            // Sets the concurrent upload task number to 5.
            uploadFileRequest.setTaskNum(5);
            // Sets the part size to 1MB.
            uploadFileRequest.setPartSize(1024 * 1024 * 1);
            // Enables the checkpoint file. By default it's off.
            uploadFileRequest.setEnableCheckpoint(true);

            UploadFileResult uploadResult = ossClient.uploadFile(uploadFileRequest);

            CompleteMultipartUploadResult multipartUploadResult =
                    uploadResult.getMultipartUploadResult();
            location = multipartUploadResult.getLocation();

            logger.info("aliyun-oss文件[{}]上传成功,新文件名:{}", uploadFile, objectFile);
//            logger.info("======" + multipartUploadResult.getETag());

        } catch (OSSException oe) {
            logger.info("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            logger.info("Error Message: " + oe.getErrorMessage());
            logger.info("Error Code:       " + oe.getErrorCode());
            logger.info("Request ID:      " + oe.getRequestId());
            logger.info("Host ID:           " + oe.getHostId());
        } catch (ClientException ce) {
            logger.info("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.");
            logger.info("Error Message: " + ce.getMessage());
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            if (shutdown) {
                ossClient.shutdown();
            }
            return location;
        }
    }

    public void shutdown() {
        try {
            ossClient.shutdown();
        } catch (Exception e) {
            logger.error("shutdown fail", e.fillInStackTrace());
        }

    }
}

三、测试

  • 测试方法
	@Autowired(required = false)
    private AliOssUtil aliOssUtil;
    
    @Test
    public void ossTest(){
        aliOssUtil.upload("C:\\Users\\kk\\Desktop\\2222.webp","test/image/2222.webp",false);
    }

  • 查看阿里云oss,图片已上传成功!
    图片上传成功

总结

参考

你可能感兴趣的:(spring,生态,阿里云oss,spring,boot,阿里云)