七牛云OSS配置

93 阅读1分钟

1. 注册账号,创建空间

这个就自己在七牛云官网创建就行

2. 引入SDK依赖

这个版本是引入7.13里最高版本

<!--七牛云OSS-->
<dependency>
    <groupId>com.qiniu</groupId>
    <artifactId>qiniu-java-sdk</artifactId>
    <version>[7.13.0, 7.13.99]</version>
</dependency>

3.上传配置

3.1 application.yml

#  七牛云oss
oss:
  qiniu:
    accessKey: 在你的七牛云秘钥中
    secretKey: 在你的七牛云秘钥中
    bucket: 你创建的存储空间
    url: 你绑定的域名或者免费的30天域名,用来访问上传成功的文件

3.3 核心类 OssConfiguration

@Data
@Component
@ConfigurationProperties("oss.qiniu")
public class OssConfiguration {

    private String accessKey;
    private String secretKey;
    private String bucket;
    private String url;
    
    // 这个Springboot引入的JSON框架,用来解析返回的数据
    @Resource
    private ObjectMapper objectMapper;

    /**
     * @function 上传文件到 OSS
     * @Time 2024/5/1 20:00
     */
    public String uploadOss(MultipartFile imgFile) {
        if (imgFile.getOriginalFilename() == null) {
            throw new ServiceException(ResponseCode.IMG_NULL_ERROR);
        }
        //默认不指定filePath的情况下,以文件内容的hash值作为文件名
        String filePath = generateFilePath(imgFile.getOriginalFilename());
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        try {
            InputStream inputStream = imgFile.getInputStream();
            Auth auth = Auth.create(ossProperties.getAccessKey(), ossProperties.getSecretKey());
            String upToken = auth.uploadToken(ossProperties.getBucket());
            Response response = uploadManager.put(inputStream, filePath, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = objectMapper.readValue(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            return ossProperties.getUrl() + filePath;
        } catch (Exception ex) {
            throw new ServiceException(ResponseCode.IMG_UPLOAD_ERROR);
        }
    }

    /**
     * @function 为了保证文件民冲突,用 日期+uuid 成功文件路径和文件名
     * @Time 2024/5/1 20:00
     */
    public String generateFilePath(String fileName) {
        //根据日期生成路径   2022/1/15/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        //uuid作为文件名
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //后缀和文件后缀一致
        int index = fileName.lastIndexOf(".");
        // test.jpg -> .jpg
        String fileType = fileName.substring(index);
        return datePath + uuid + fileType;
    }
}