1, OSS introduction
Alibaba cloud Object Storage Service (OSS) is a massive, secure, low-cost and highly reliable cloud storage service provided by Alibaba cloud. OSS can be used to store massive files such as pictures, audio and video, logs, etc. Various terminal devices, Web site programs and mobile applications can directly write or read data to the OSS.
2, Related concepts in OSS
- Endpoint: access the domain name. Through this domain name, you can access the API of OSS service for file upload, download and other operations.
- Bucket: storage space is a container for storing objects. All storage objects must belong to a storage space.
- Object: object, which is the basic unit for OSS to store data, also known as OSS file
- AccessKey: access key, which refers to the AccessKeyId and AccessKeySecret used in access authentication.
3, OSS related settings
Open OSS service
- Log in to Alibaba cloud's official website;
- Move the mouse to the product tab, click object storage OSS, and open the OSS product details page;
- On the OSS product details page, click open now.
Create storage space
-
Click the console button in the upper right corner of the web page to enter the console
-
Select the object storage OSS in my cloud product
-
New storage space
-
Create a new storage space and set the read-write permission to public read
4, OSS server direct transmission
introduce
Every OSS user will use the upload service. The common upload method on the Web side is that users upload files to the application server on the browser or App side, and then the application server uploads the files to OSS. The specific process is shown in the figure below.
Compared with direct data transmission to OSS, the above method has three disadvantages:
- Slow upload: user data needs to be uploaded to the application server before being uploaded to OSS. The network transmission time is twice as long as that of direct transmission to OSS. If the user data is not transferred through the application server, but directly transmitted to the OSS, the speed will be greatly improved. Moreover, OSS adopts BGP bandwidth, which can ensure the transmission speed between local operators.
- Poor scalability: if there are many subsequent users, the application server will become a bottleneck.
- High cost: multiple application servers need to be prepared. Since the OSS upload traffic is free, if the data is directly transmitted to the OSS without passing through the application server, several application servers will be saved.
Case process
Every OSS user will use the upload service. The common upload method on the Web side is that users upload files to the application server on the browser or App side, and then the application server uploads the files to OSS.
Add permissions for users
Then set the KeyID and KeySecret
Run the test and you can see success in the cloud
The code can refer to the documentation on the official website
Official website learning: https://help.aliyun.com/document_detail/32007.html
// Endpoint takes Chengdu as an example. Please fill in other regions according to the actual situation. String endpoint = "http://Own bucket address "; // The cloud account AccessKey has all API access rights. It is recommended to follow Alibaba cloud security best practices and create and use RAM sub accounts for API access or daily operation and maintenance. Please log in https://ram.console.aliyun.com establish. // 1. Create RAM sub account // 2. Obtain accesskeyid accesskeysecret // 3. Set permissions for child users String accessKeyId = "own accessKeyId "; String accessKeySecret = "own accessKeySecret"; // Create an OSSClient instance. OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); //Get the current date, and you can create a folder for management every day SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); String dir = simpleDateFormat.format(new Date())+"/"; // Upload file stream. InputStream inputStream = new FileInputStream("D:\\image\\8517911.jpg"); ossClient.putObject("biao-bucket02", dir+"8517911.jpg", inputStream); // Close the OSSClient. ossClient.shutdown(); System.out.println("Upload succeeded!");
5, OSS front end direct transmission - back end signature
1. Introduction
Official website case
The Web side requests a signature from the server and then uploads it directly, which will not put pressure on the server, and it is safe and reliable. However, the server in this example cannot know how many files the user has uploaded and what files have been uploaded in real time. If you want to know what files the user has uploaded in real time, you can use the server signature direct transmission and set the upload callback.
Process introduction
- The Web front end requests the application server to obtain the parameters required for uploading (such as OSS accessKeyId, policy, callback and other parameters)
- The application server returns relevant parameters
- The Web front end directly initiates a file upload request to the OSS service
- After uploading, the OSS service will call back the callback interface of the application server (not implemented)
- The application server returns a response to the OSS service (not implemented)
- The OSS service returns the contents of the application server callback interface to the Web front end
2. Integrate OSS to upload files
2.1 add related dependencies in pom.xml
<!--OSS SDK--> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.10.2</version> </dependency>
2.2 write a Controller at the back end for back-end signature
import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.common.utils.BinaryUtil; import com.aliyun.oss.model.MatchMode; import com.aliyun.oss.model.PolicyConditions; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; @RestController public class OSSController { //Resolve request cross domain annotations @CrossOrigin @RequestMapping("/oss/policy") public Map<String,String> policy(){ String accessId = "LTAI4GHWCM5"; // Please fill in your AccessKeyId. String accessKey = "Vytl0LAIKGmiWATIuuwe"; // Please fill in your AccessKeySecret. String endpoint = "oss-cn-chengdu.aliyuncs.com"; // Please fill in your endpoint. String bucket = "mall-biao"; // Please fill in your bucket name. String host = "https://" + bucket + "." + endpoint; // The format of host is bucketname.endpoint SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); String date = simpleDateFormat.format(new Date()); String dir = "tuling-test/"+date+"/"; // Prefix specified when the user uploads the file. // Create an OSSClient instance. OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey); try { long expireTime = 30; long expireEndTime = System.currentTimeMillis() + expireTime * 1000; Date expiration = new Date(expireEndTime); // The maximum supported file size requested by PostObject is 5 GB, that is, CONTENT_LENGTH_RANGE is 5 * 1024 * 1024 * 1024. PolicyConditions policyConds = new PolicyConditions(); policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000); policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir); String postPolicy = ossClient.generatePostPolicy(expiration, policyConds); byte[] binaryData = postPolicy.getBytes("utf-8"); String encodedPolicy = BinaryUtil.toBase64String(binaryData); String postSignature = ossClient.calculatePostSignature(postPolicy); Map<String, String> respMap = new LinkedHashMap<String, String>(); respMap.put("accessid", accessId); respMap.put("policy", encodedPolicy); respMap.put("signature", postSignature); respMap.put("dir", dir); respMap.put("host", host); respMap.put("expire", String.valueOf(expireEndTime / 1000)); // respMap.put("expire", formatISO8601Date(expiration)); return respMap; } catch (Exception e) { // Assert.fail(e.getMessage()); System.out.println(e.getMessage()); } finally { ossClient.shutdown(); } return null; } }
2.3 front end direct transmission - back end signature
vue case code
<template> <el-upload class="upload-demo" :action="objData.host" :file-list="fileList" :before-upload="ossPolicy" :data="objData" list-type="picture"> <el-button size="small" type="primary">Click upload</el-button> <div slot="tip" class="el-upload__tip">Upload only jpg/png Documents, and no more than 500 kb</div> </el-upload> </template> <script> export default { data() { return { fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}], objData:{ OSSAccessKeyId:'', policy:'', Signature:'', key:'', host:'', dir:'' } }; }, methods: { ossPolicy(file){ let _self=this; // Stop uploading directly return false; // Sign the server before uploading return new Promise((resolve,reject)=>{ // Request backend this.axios.get('http://localhost:8088/oss/policy') // When using the arrow function this points to the outer layer .then(response =>{ _self.objData.OSSAccessKeyId=response.data.accessid; _self.objData.policy=response.data.policy; _self.objData.Signature=response.data.signature; _self.objData.dir=response.data.dir; _self.objData.host=response.data.host; // Direct OSS server address _self.objData.key=response.data.dir+"${filename}"; resolve(true); // Continue uploading }) .catch(function (error) { console.log(error); reject(false) // Stop uploading }); }); } } } </script> <style> </style>