阿里云OSS

阿里云OSS

用户认证需要上传证件图片、首页轮播也需要上传图片,因此我们要做文件服务,阿里云oss是一个很好的分布式文件服务系统,所以只需要集成阿里云oss即可

1. 开通”对象存储OSS”服务

1.1 创建Bucket

类似于包

选择:低频访问存储、公共读、不开通

1.2 上传默认头像

可以创建专门的文件夹,用来存放用户头像

2. 使用sdk文档

参考文档:https://help.aliyun.com/document_detail/32011.html

3. 整合

3.1 搭建service-oss模块

  1. 引入依赖

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <!-- 阿里云oss依赖 -->
    <dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    </dependency>

    <!-- 日期工具依赖 -->
    <dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    </dependency>
  2. 添加配置文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    # 服务端口
    server.port=8205
    # 服务名
    spring.application.name=service-oss

    #返回json的全局时间格式
    spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
    spring.jackson.time-zone=GMT+8

    spring.redis.host=192.168.134.134
    spring.redis.port=6379
    spring.redis.database= 0
    spring.redis.timeout=1800000
    spring.redis.lettuce.pool.max-active=20
    spring.redis.lettuce.pool.max-wait=-1
    #最大阻塞等待时间(负数表示没限制)
    spring.redis.lettuce.pool.max-idle=5
    spring.redis.lettuce.pool.min-idle=0

    # nacos服务地址
    spring.cloud.nacos.discovery.server-addr=localhost:8848

    aliyun.oss.endpoint=oss-cn-chengdu.aliyuncs.com
    aliyun.oss.accessKeyId=LTAI5tFx8hiRkEwAVhiLCE9F
    aliyun.oss.secret=719P8hAbQJL20VnQkbmUrLOey4i8NC
    aliyun.oss.bucket=appointment-register-cpg

    spring.servlet.multipart.max-file-size=50MB
  3. 创建启动类

    1
    2
    3
    4
    5
    6
    7
    8
    @SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
    @EnableDiscoveryClient
    @ComponentScan(basePackages = {"com.CPG"})
    public class ServiceOssApplication {
    public static void main(String[] args) {
    SpringApplication.run(ServiceOssApplication.class,args);
    }
    }
  4. 在网关中配置

    1
    2
    3
    4
    5
    6
    #设置路由id
    spring.cloud.gateway.routes[5].id=service-oss
    #设置路由的uri
    spring.cloud.gateway.routes[5].uri=lb://service-oss
    #设置路由断言,代理servicerId为auth-service的/auth/路径
    spring.cloud.gateway.routes[5].predicates= Path=/*/oss/**

3.2 测试SDK

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public static void main(String[] args) throws Exception {
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "https://oss-cn-chengdu.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = "LTAI5tFx8hiRkEwAVhiLCE9F";
String accessKeySecret = "719P8hAbQJL20VnQkbmUrLOey4i8NC";
// 填写Bucket名称,例如examplebucket。
String bucketName = "appointment-register-cpg";

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

try {
// 创建存储空间。
ossClient.createBucket(bucketName);

} 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
ossClient.shutdown();
}
}
}

3.2 编写接口

  1. 创建ConstantOssPropertiesUtils工具类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    @Component
    public class ConstantOssPropertiesUtils implements InitializingBean {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.secret}")
    private String secret;

    @Value("${aliyun.oss.bucket}")
    private String bucket;

    public static String END_POINT;
    public static String ACCESS_KEY_ID;
    public static String SECRET;
    public static String BUCKET;


    @Override
    public void afterPropertiesSet() throws Exception {
    END_POINT = endpoint;
    ACCESS_KEY_ID = accessKeyId;
    SECRET = secret;
    BUCKET = bucket;
    }
    }
  2. 创建接口实现类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    @Service
    public class FileServiceImpl implements FileService {

    @Override
    public String upload(MultipartFile file) {
    // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
    String endpoint = ConstantOssPropertiesUtils.END_POINT;
    // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
    String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
    String accessKeySecret = ConstantOssPropertiesUtils.SECRET;
    // 填写Bucket名称,例如examplebucket。
    String bucketName = ConstantOssPropertiesUtils.BUCKET;

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

    InputStream inputStream = null;
    try {
    inputStream = file.getInputStream();
    } catch (IOException e) {
    e.printStackTrace();
    }

    // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
    String objectName = file.getOriginalFilename();
    //生成随机唯一值,使用uuid,添加到文件名称里
    String uuid = UUID.randomUUID().toString().replaceAll("-","");
    objectName = uuid+objectName;

    //按照当前日期创建文件夹,并将文件上传到创建的文件夹中
    String timeUrl = new DateTime().toString("yyyy/MM/dd");
    objectName = timeUrl+"/"+objectName;

    // 创建PutObject请求,调用方法实现上传。
    ossClient.putObject(bucketName, objectName, inputStream);

    //关闭OSSClient
    ossClient.shutdown();

    //上传后文件路径
    String url = "https://"+bucketName+"."+endpoint+"/"+objectName;

    return url;
    }
    }
  3. 创建controller接口

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    @RestController
    @RequestMapping("/api/oss/file")
    public class FileApiController {

    @Autowired
    private FileService fileService;

    //上传文件到阿里云oss
    @PostMapping("fileUpload")
    public Result fileUpload(MultipartFile file){
    //获取上传的文件
    String url = fileService.upload(file);
    return Result.ok(url);
    }
    }

本站由 Cccccpg 使用 Stellar 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。