当前位置:网站首页>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 !
边栏推荐
- Performance analysis of continuous time system (1) - performance index and first and second order analysis of control system
- Docker - docker installation, MySQL installation on docker, and project deployment on docker
- C static method and non static method
- The understanding of string in C.
- Typescript installation
- express
- Selenium automated test interview questions family bucket
- I'm afraid I won't use the JMeter interface testing tool if I accept this practical case
- Selenium自动化测试面试题全家桶
- Unity display Kinect depth data
猜你喜欢

MongoDB学习笔记(1)——安装MongoDB及其相关配置

阿里云视频点播服务的开通和使用

Jmeter接口自动化-如何解决请求头Content-Type冲突问题

Product recommendation and classified product recommendation

转行软测&跳槽到新公司,工作怎样快速上手?
![[wechat applet] project practice - lottery application](/img/08/1e8643c95ad7c2661a76f9c3a0c57d.png)
[wechat applet] project practice - lottery application

I'm afraid I won't use the JMeter interface testing tool if I accept this practical case

express

Kinect2 for unity3d - avatardemo learning

express get/post/delete...请求
随机推荐
微机原理学习笔记-通用整数指令及应用
v-if,v-else,v-for
Docker - docker installation, MySQL installation on docker, and project deployment on docker
C interface knowledge collection suggestions collection
MySQL学习笔记(2)——存储过程与存储函数
Day 3 of leetcode question brushing
转行软测&跳槽到新公司,工作怎样快速上手?
Big enemies, how to correctly choose the intended enterprises in the new testing industry?
200行代码快速入门文档型数据库MonogoDB
Unity shows Kinect captured shots
Imitation thread deduction
Hash、Set、List、Zset、BitMap、Scan
Power control
进行接口测试时,连接数据库,对数据源进行备份、还原、验证操作
Latex使用-控制表格或者图形的显示位置
2022备战秋招10W字面试小抄pdf版,附操作系统、计算机网络面试题
asp.net 的经验
【微信小程序】项目实战—抽签应用
npm、cnpm 淘宝镜像
用函数在Excel中从文本字符串提取数字