当前位置:网站首页>Opening and using Alibaba cloud object storage OSS
Opening and using Alibaba cloud object storage OSS
2022-07-27 19:10:00 【Xiao Li, who loves traveling】
Alibaba cloud object storage OSS Opening and use of
List of articles
Preface :
The practical part of this blog is for me SpringBoot+Vue Written for online education project .
One 、 Open alicloud OSS
1 Enter alicloud's official website , Find Alibaba cloud object storage OSS entrance 
2 Click on the object store OSS
3 Click to open the service 
4 Agree to the agreement , Click open now 
5 Click management console 
6 Click Create Bucket
7 establish Bucket
8 Upload files 
9 Upload any image 
10 Now you can view the pictures , You can see URL Information 
Two 、 Opening AccessKey
1 Click on AccessKey
2 Continue to use AccessKey
3 Mobile phone verification 
4 You can see the secret key information 
5 Click save AK Information , Will automatically download a csv file 
6 Click the learning path 
7 Click on Java SDK
8 You can view alicloud OSS Official documents of 
3、 ... and 、 Project practice Use Java SDK operation OSS
Combine my Springboot+Vue Online education project , Integrating Alibaba cloud OSS
1 First, we need to introduce Alibaba cloud OSS Related dependencies , Refer to official documents
<!--aliyunOSS--> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>${aliyun.oss.version}</version> </dependency>
2 stay service Layer creation service_oss modular 
3 stay pom.xml Add dependency to
<dependencies>
<!-- Alibaba cloud oss rely on -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
</dependency>
<!-- The date toolbar depends on -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
</dependencies>
4 Writing configuration files application.properties
Be careful :OSS No space is allowed before or after the relevant configuration
# Port number
server.port=8002
# service name
spring.application.name=service-oss
# Environment settings
spring.profiles.active=dev
# Integrate Alibaba cloud OSS
aliyun.oss.file.endpoint=
aliyun.oss.file.keyid=
aliyun.oss.file.keysecret=
# bucket You can create... In the console , You can also use java Code creation
aliyun.oss.file.bucketname=
5 Write the startup class OssApplication.java
Be careful : To exclude data source loading , Need to be in SpringBootApplication To add execude=DataSourceAutoConfiguration.class
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)// Do not load the data source
@ComponentScan(basePackages = {
"com.atguigu"})
public class OssApplication {
public static void main(String[] args) {
SpringApplication.run(OssApplication.class,args);
}
}
6 Write configuration tool class
Be careful : This tool class needs to be added Component annotation , And need to realize InitializingBean Interface , rewrite afterPropertiesSet() Method , The purpose is to take advantage of the defined private attributes .
// When the project starts ,spring There's an interface ,spring After loading , Execute an interface method
@Component
public class ConstantPropertiesUtils implements InitializingBean {
// I. startup project , This class will initialize
// Read the contents of the configuration file
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;
@Value("${aliyun.oss.file.keyid}")
private String keyId;
@Value("${aliyun.oss.file.keysecret}")
private String keySecret;
@Value("${aliyun.oss.file.bucketname}")
private String bucketName;
// Define open static constants
public static String END_POINT;
public static String ACCESS_KEY_ID;
public static String ACCESS_KEY_SECRET;
public static String BUCKET_NAME;
@Override
public void afterPropertiesSet() throws Exception {
END_POINT = endpoint;
ACCESS_KEY_ID = keyId;
ACCESS_KEY_SECRET = keySecret;
BUCKET_NAME = bucketName;
}
}
7 service layer
You can view alicloud OSS Official documents , Make changes 
OssService.java
public interface OssService {
// Upload avatar to OSS
String uploadOssFileAvatar(MultipartFile file);
}
OssServiceImpl.java
Be careful : Why return the final... Of the uploaded object url, because controller To put the url As the response body information, it is passed into . Alibaba cloud OSS Official documents did not find direct access to this url Methods , You need to splice strings manually .
@Service
public class OssServiceImpl implements OssService {
@Override
public String uploadOssFileAvatar(MultipartFile file) {
// Get... Through the tool class
String endpoint = ConstantPropertiesUtils.END_POINT;
String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
// Upload file stream .
InputStream inputStream = null;
try {
// establish OSSClient example .
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// Get the input stream of the uploaded file
inputStream = file.getInputStream();
// Get the file name
String filename = file.getOriginalFilename();
// call oss Method upload
// The first parameter : Bucket name The second parameter : Upload to oss File path and file name /aa/bb/1.jpg The third parameter : Input stream for uploading files
ossClient.putObject(bucketName, filename, inputStream);
// close OSSClient.
ossClient.shutdown();
// Return the uploaded file path to
// https://edu-0912.oss-cn-beijing.aliyuncs.com/4c480a7029cbea756e87d34940654825.jpg
return "https://" + bucketName + "." + endpoint + "/" + filename;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
8 controller
Be careful : Need to be in controller Add @CrossOrign annotation , Open cross domain requests
@RestController
@RequestMapping(path = "/eduoss")
@CrossOrigin
public class OssController {
@Autowired
private OssService ossService;
// How to upload avatars
@PostMapping("/uploadOssFile")
public R uploadOssFileAvatar(MultipartFile file){
// Get uploaded files MultipartFile
String url = ossService.uploadOssFileAvatar(file);
return R.ok().data("url",url);
}
}
9 Start the project ,Swagger test
Get into swagger, It's time to start debugging 
10 Upload files 
11 OSS Background view , You can find an additional picture 
12 Project structure
service_oss The function of the module is to add avatars to lecturers 
Conclusion :

Level co., LTD. , For reference only , If there is any mistake , Hope to point out at any time !
边栏推荐
- 2022备战秋招10W字面试小抄pdf版,附操作系统、计算机网络面试题
- The great idea of NS2
- MySQL 01 relational database design
- JDBC MySQL 02 data access and Dao mode
- MySQL 04 advanced query (II)
- npm、cnpm 淘宝镜像
- express
- Unity学习笔记(实现传送带)
- Latex use - subfigure vertical graphics
- C # interaction with MySQL database - MySQL configuration and addition, deletion, query and modification operations
猜你喜欢

Nodejs template engine EJS

转行软测&跳槽到新公司,工作怎样快速上手?

web UI 自动化测试:Selenium 语法详解 史上最全

Kinect2 for unity3d - avatardemo learning

200行代码快速入门文档型数据库MonogoDB

一篇让你掌握线程和线程池,还解决了线程安全问题,确定不看看?

Big enemies, how to correctly choose the intended enterprises in the new testing industry?

MySQL 03 advanced query (I)

NPM's ID card and dependence

自控原理学习笔记-系统稳定性分析(1)-BIBO稳定及Routh判据
随机推荐
Questions about webservice
Unity learning notes (rigid body physics collider trigger)
Some advice for NS2 beginner.
Code interview of Amazon
Dynamic proxy
Performance analysis of continuous time systems (2) - second order system performance improvement methods PID, PR
CMD 命令
Greedy method, matroid and submodular function (refer)
[wechat applet] project practice - lottery application
Unity显示Kinect捕获的镜头
web UI 自动化测试:Selenium 语法详解 史上最全
Unity shows Kinect captured shots
微机原理学习笔记-常见寻址方式
电磁场学习笔记-矢量分析和场论基础
v-if,v-else,v-for
Resource for NS2 beginner
Nacos集群部署-高可用保证
Kinect for unity3d - backgroundremovaldemo learning
用Matlab生成适用于期刊及会议的图形- plot
图的遍历的定义以及深度优先搜索和广度优先搜索(二)