当前位置:网站首页>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 !
边栏推荐
- MySQL 06 transaction, view, index, backup and recovery
- Resource for NS2 beginner
- 一个经验
- Word 2007+ tips
- Latex use - control the display position of tables or graphics
- C # interaction with MySQL database - MySQL configuration and addition, deletion, query and modification operations
- Blog Garden beautification tutorial
- Power control
- C file and folder input / output stream code
- ES6数值的扩展
猜你喜欢
随机推荐
asp. Net experience
Some advice for NS2 beginner.
asp.net 的经验
Unity learning notes (rigid body physics collider trigger)
Collection of software design suggestions of "high cohesion and low coupling"
Hash、Set、List、Zset、BitMap、Scan
Ruiji takeout notes
npm 基本使用
又有一个Repeater的例子
MongoDB
An article allows you to master threads and thread pools, and also solves thread safety problems. Are you sure you want to take a look?
ES6-新增方法
Resource for NS2 beginner
CMD 命令
v-if,v-else,v-for
WSN Journal indexed by SCI(转)
IDEA连接数据库时区问题,报红Server returns invalid timezone. Need to set ‘serverTimezone‘ property.
Leetcode first day of question brushing
Acquisition data transmission mode and online monitoring system of vibrating wire wireless acquisition instrument for engineering instruments
SSM project uses filter to realize login monitoring









