When we are developing projects, we often need to upload files, pictures, etc. For many projects, although there are file storage server technologies such as FastDFS, there is actually no need for us to build our own image file servers. For a small non-professional application, building your own exclusive file storage server is a waste, and your company may not necessarily have that technical strength.
However, our projects often require uploading and downloading various files such as pictures. So how to achieve this?
Here Yige recommends to everyone to use Alibaba Cloud storage, which is cheap and reliable! So today Yige will take you to learn how to use Alibaba Cloud's OSS to implement file uploads.
1. Introduction to Alibaba Cloud OSS
1. Introduction to Storage Service
Alibaba Cloud provides an object storage OSS service, which can realize massive, secure, low-cost and high-reliability cloud storage services, providing 99.99999999999999% data reliability. And using the RESTful API, you can store and access anywhere in the Internet, with elastic expansion of capacity and processing capabilities, and a variety of storage types to choose from, comprehensively optimize storage costs.
2. Purchase Alibaba Cloud OSS service
. The first choice is to search Alibaba Cloud, and choose the first one.

Then select the object storage OSS product in the cloud computing foundation.


You can see that 40G storage service is only 9 yuan per year, which is very cheap and is enough for learning.

3. Alibaba Cloud OSS console
Click the console link on the home page to enter the background.


Create a Bucket bucket here as the space to store the file.

bucket name cannot be repeated.

can create subdirectories in its own bucket space to store files under different projects or modules.

Next, you need to set the access permissions of this directory, which can be set to public read.

Set the authorization policy of the bucket again.


2. Implement OSS cloud storage in SpringBoot
1. Create a web project
We create a web program according to previous experience and transform it into a Spring Boot project. The specific process is omitted.

2. Add dependency package
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scope/dependency!--Simplify bean code--dependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactId/dependency!--Simplify bean code--dependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactId/dependency!-- Thymeleaf--dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-thymeleaf/artifactId/dependency!-- Picture upload SDK Alibaba Cloud oss --dependencygroupIdcom.aliyun.oss/groupIdartifactIdaliyun-sdk-oss/artifactIdversion2.8.3/version/dependencydependencygroupIdcommons-Fileupload/groupIdartifactIdcommons-fileupload/artifactIdversion1.3.1/version/dependency3. Create configuration information
You can view the AccessKey information of your Alibaba Cloud account here.
When we are developing projects, we often need to upload files, pictures, etc. For many projects, although there are file storage server technologies such as FastDFS, there is actually no need for us to build our own image file servers. For a small non-professional application, building your own exclusive file storage server is a waste, and your company may not necessarily have that technical strength.
However, our projects often require uploading and downloading various files such as pictures. So how to achieve this?
Here Yige recommends to everyone to use Alibaba Cloud storage, which is cheap and reliable! So today Yige will take you to learn how to use Alibaba Cloud's OSS to implement file uploads.
1. Introduction to Alibaba Cloud OSS
1. Introduction to Storage Service
Alibaba Cloud provides an object storage OSS service, which can realize massive, secure, low-cost and high-reliability cloud storage services, providing 99.99999999999999% data reliability. And using the RESTful API, you can store and access anywhere in the Internet, with elastic expansion of capacity and processing capabilities, and a variety of storage types to choose from, comprehensively optimize storage costs.
2. Purchase Alibaba Cloud OSS service
. The first choice is to search Alibaba Cloud, and choose the first one.

Then select the object storage OSS product in the cloud computing foundation.


You can see that 40G storage service is only 9 yuan per year, which is very cheap and is enough for learning.

3. Alibaba Cloud OSS console
Click the console link on the home page to enter the background.


Create a Bucket bucket here as the space to store the file.

bucket name cannot be repeated.

can create subdirectories in its own bucket space to store files under different projects or modules.

Next, you need to set the access permissions of this directory, which can be set to public read.

Set the authorization policy of the bucket again.


2. Implement OSS cloud storage in SpringBoot
1. Create a web project
We create a web program according to previous experience and transform it into a Spring Boot project. The specific process is omitted.

2. Add dependency package
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scope/dependency!--Simplify bean code--dependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactId/dependency!--Simplify bean code--dependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactId/dependency!-- Thymeleaf--dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-thymeleaf/artifactId/dependency!-- Picture upload SDK Alibaba Cloud oss --dependencygroupIdcom.aliyun.oss/groupIdartifactIdaliyun-sdk-oss/artifactIdversion2.8.3/version/dependencydependencygroupIdcommons-Fileupload/groupIdartifactIdcommons-fileupload/artifactIdversion1.3.1/version/dependency3. Create configuration information
You can view the AccessKey information of your Alibaba Cloud account here.


bucketName: "yiyige" accessKeyId: "Own Alibaba Cloud's accessKey" accessKeySecret: "Own Alibaba Cloud's accessKey"#OSS corresponding area endpoint: "http://oss-cn-hangzhou.aliyuncs.com"filehost: "images"4. Create configuration information class
package com.yyg.boot.config;import lombok.Data;import lombok.Getter;import lombok.Setter;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Configuration;import org.springframework.stereotype.Component;/** * Read the configuration information in the configuration file into this class. */@Data@Configurationpublic class OssConfiguration {@Value("${endpoint}")private String endPoint;@Value("${accessKeyId}")private String accessKeyId;@Value("${accessKeySecret}")private String accessKeySecret;@Value("${filehost}")private String fileHost;@Value("${bucketName}")private String bucketName;}5. Encapsulate Alibaba Cloud file upload tool class
package com.yyg.boot.util;import com.aliyun.oss.OSSClient;import com.aliyun.oss.model.CannedAccessControlList;import com.aliyun.oss.model.CreateBuckettml1Requesttml2;import com.aliyun.oss.model.PutObjectRequest;import com.aliyun.oss.model.PutObjectResult;import com.yyg.boot.config.OssConfiguration;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import java.io.File;import java.text.SimpleDateFormat;import java.util.Date;import java.util.UUID;/** * Encapsulated file upload method */@Componentpublic class AliyunOssUtil {@Autowiredprivate OssConfiguration config;public String upload(File file) {if (file == null) {return null;}String endPoint = config.getEndPoint();String keyId = config.getAccessKeyId();String keySecret = config.getAccessKeySecret();String bucketName = config.getBucketName();String fileHost = config.getFileHost();//Define the format of the subfile SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");String dateStr = format.format(new Date());//Ali Cloud file upload client OSSClient client = new OSSClient(endPoint, keyId, keySecret);try {//Determine whether the bucket exists if (!client.doesBucketExist(bucketName)) {//Create a bucket client.createBucket(bucketName);CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);//Set access permissions to public read createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);//Start the request to create a bucket client.createBucket(createBucketRequest);}//When the bucket exists, upload the file//Set the file path and name String fileUrl = fileHost + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName());PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, fileUrl, file));client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);//After the file is uploaded successfully, return the path of the current file if (result != null) {return fileUrl;}} catch (Exception e) {e.printStackTrace();} finally {if (client != null) {client.shutdown();}}return null;}}6. Write Controller interface
package com.yyg.boot.web;import com.yyg.boot.util.AliyunOssUtil;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.steretype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.multipart.MultipartFile;import java.io.File;import java.io.FileOutputStream;@Controllerpublic class OssController {@Autowiredprivate AliyunOssUtil ossUtil;@GetMapping("/")public String showUploadFile() {return "upLoad";}@PostMapping("/uploadFile")public String upload(@RequestParam("file") MultipartFile file) {try {if (file != null) {String fileName = file.getOriginalFilename();if (!"".equals(fileName.trim())) {File newFile = new File(fileName);FileOutputStream os = new FileOutputStream(newFile);os.write(file.getBytes());os.close();//Copy the content in the file to the Ao newFile file.transferTo(newFile);String upload = ossUtil.upload(newFile);//Images echo address://http://yiyige.oss-cn-hangzhou.aliyuncs.com/images/2019-10-21/6c964702b67d4eeb920e7f1f4358189b-dishu.jpgSystem.out.println("path=" + upload);}}} catch (Exception e) {e.printStackTrace();}return "success";}}7. Write file upload page
!DOCTYPE htmlhtml xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" headmeta charset="UTF-8"/title【OSS-based upload file page】/titlelink rel="stylesheet" th:href="@{/css/bootstrap.min.css}"media="all"/style type="text/css"*{margin:0;padding:0;}#group{position: absolute;left:580px;}#submit{position: absolute;top:140px;left:580px;}/style/headbodydiv align="center"h2 style="color:orangered;"OSS-based upload file page/h2/divbr/form action="/uploadFile" enctype="multipart/form-data" method="post"div class="form-group" id="group"label for="exampleInputFile"File input/labelinput type="file" id="exampleInputFile" name="file"//divbutton type="submit" class="btn btn-default" id="submit" Upload/button/form/body/html8. File upload successful interface
!DOCTYPE htmlhtmlhtml xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" headmeta charset="UTF-8"/title【File upload successful page】/title/headbodydiv align="center"h5 upload successfully/h5/div/body/html9. Write the entry class
package com.yyg.boot;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class OssApplication {public static void main(String[] args) {SpringApplication.run(OssApplication.class, args);}}10. Test
First enter the file upload interface and select a file to upload.

uploaded successfully.

Open the console and you can see the image path returned by Alibaba Cloud OSS server.

Then we go to Alibaba Cloud server and see that a folder is automatically created with the date of the day, and the files uploaded on the day are stored here.

See the image file you just uploaded in this folder.

Conclusion
So far, Yige has introduced the tutorial on using Alibaba Cloud OSS to you. Have you learned it now? Finally, , Yi Ge can secretly tell you a little secret. You can use Alibaba Cloud OSS to build your own private "cloud disk". As for what content is stored in it, you can understand it yourself!
Author: Yiyi Ge Sun
Link: https://juejin.cn/post/7178627128269733949
Source: Rare Earth Nuggets

uploaded successfully.

Open the console and you can see the image path returned by Alibaba Cloud OSS server.

Then we go to Alibaba Cloud server and see that a folder is automatically created with the date of the day, and the files uploaded on the day are stored here.

See the image file you just uploaded in this folder.

Conclusion
So far, Yige has introduced the tutorial on using Alibaba Cloud OSS to you. Have you learned it now? Finally, , Yi Ge can secretly tell you a little secret. You can use Alibaba Cloud OSS to build your own private "cloud disk". As for what content is stored in it, you can understand it yourself!
Author: Yiyi Ge Sun
Link: https://juejin.cn/post/7178627128269733949
Source: Rare Earth Nuggets