Springboot整合阿里云OSS进行文件上传

发布于:2022-08-05 ⋅ 阅读:(443) ⋅ 点赞:(0)

本篇文章我们来介绍如何用Springboot整合阿里云OSS进行文件上传。

 

1、开通阿里云OSS

第一步:点击立即开通

https://www.aliyun.com/product/oss

第二步:进入管理控制台

第三步:查看API帮助文档

https://help.aliyun.com/document_detail/31947.html?spm=5176.8465980.help.dexternal.41231450z6Cv3R

2、创建 bucket

存储类型:低频访问存储

读写权限:公共读

3、创建子账户

https://ram.console.aliyun.com/users

第一步:点击创建用户

第二步:填写相关信息,然后点击确定

开通完成之后,就会有个 AccessKey ID 和 AccessKey Secret。

PS:创建账户后,开通了 Open API 调用访问,要及时保存 AccessKey,否则关闭后无法再次获取。

4、给子账户分配OSS管理权限

添加OSS权限

5、整合SDK-OSS

https://github.com/alibaba/aliyun-spring-boot/blob/master/aliyun-spring-boot-samples/aliyun-oss-spring-boot-sample/README-zh.md

5.1 引入依赖 liyun-oss-spring-boot-starter

在 gulimall-common 模块中引入:

PS:这里和官方引入的依赖不一样。

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alicloud-oss</artifactId>
    <version>2.2.0.RELEASE</version>
</dependency>

5.2 在配置文件中配置 OSS 服务对应的 accessKey、secretKey 和 endpoint。

spring:
  cloud:
    alicloud:
      oss:
        endpoint: 
      access-key: 
      secret-key: 

5.3 测试

package com.atguigu.gulimall.product;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.atguigu.gulimall.product.entity.BrandEntity;
import com.atguigu.gulimall.product.service.BrandService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

@SpringBootTest
class GulimallProductApplicationTests {

    @Autowired
    OSSClient ossClient;

    @Test
    public void testUpload() throws FileNotFoundException {
        //上传文件流。
        InputStream inputStream = new FileInputStream("/Users/yushuai/Downloads/idea.jpeg");
        ossClient.putObject("itcoke", "test.jpeg", inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();
        System.out.println("上传成功.");
    }

}
本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到