Spring Boot with Alibaba Cloud Object Storage Service

Overview

Prerequisites

Concepts

Dependencies

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alicloud-oss</artifactId>
<version>0.2.1.RELEASE</version>
</dependency>

Connect to OSS

spring.application.name=spring-alibaba-ossserver.port=8080spring.cloud.alicloud.access-key=******fill***yours****here****
spring.cloud.alicloud.secret-key=******fill***yours****here****
spring.cloud.alicloud.oss.endpoint=oss-cn-hangzhou-internal.aliyuncs.com
management.endpoints.web.exposure.include=*

Use OSSClient to Save/Query Data

@Autowired
private OSS ossClient;
ossClient.createBucket("Bucket name goes here");
ossClient.doesBucketExist("Bucket name goes here");
ossClient.putObject("oss-test", "spring-alibaba-oss.json", this
.getClass().getClassLoader().getResourceAsStream("spring-alibaba-oss.json"));
OSSObject ossObject = ossClient.getObject("oss-test", "spring-alibaba-oss.json");
ossClient.deleteObject("oss-test", "spring-alibaba-oss.json");
ossClient.doesObjectExist("oss-test", "spring-alibaba-oss.json")
@GetMapping("/buckets/exist/{bucketName}")
public boolean bucketExists(@PathVariable String bucketName) {
return ossClient.doesBucketExist(bucketName);
}
@GetMapping("/objects/exist/{objectName}")
public boolean objectExists(@PathVariable String objectName) {
return ossClient.doesObjectExist(SpringAlibabaOssApplication.BUCKET_NAME, objectName);
}
@GetMapping("/upload")
public String upload() {
try {
ossClient.putObject("oss-test", "spring-alibaba-oss.json", this
.getClass().getClassLoader().getResourceAsStream("spring-alibaba-oss.json"));
} catch (Exception e) {
e.printStackTrace();
return "upload fail: " + e.getMessage();
}
return "upload success";
}
@GetMapping("/download")
public String download() {
try {
OSSObject ossObject = ossClient.getObject(SpringAlibabaOssApplication.BUCKET_NAME, "spring-alibaba-oss.json");
return "download success, content: " + IOUtils
.readStreamAsString(ossObject.getObjectContent(), CharEncoding.UTF_8);
} catch (Exception e) {
e.printStackTrace();
return "download fail: " + e.getMessage();
}
}

Conclusion

Reference

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store