当前位置:网站首页>[OSS file upload quick start]
[OSS file upload quick start]
2022-04-23 06:57:00 【One duck, one duck】
One 、OSS Introduce
Alibaba cloud object storage service (Object Storage Service, abbreviation OSS), It's a huge amount provided by Alibaba cloud 、 Security 、 Low cost 、 Highly reliable cloud storage service service .OSS Can be used for pictures 、 Audio and video 、 Log and other massive file storage . All kinds of terminal devices 、Web Website program 、 Mobile applications can go directly to OSS Write or read Take the data .
Two 、OSS Related concepts in
- Endpoint: Access to the domain name , Through this domain name you can access OSS Service API, Upload files 、 Download and other operations .
- Bucket: Storage space , It's a container for storing objects , All storage objects must belong to a storage space .
- Object: object , The object is OSS The basic unit for storing data , Also known as OSS The file of
- AccessKey: Access key , It's used in access authentication AccessKeyId and AccessKeySecret.
3、 ... and 、OSS Related Settings
Opening OSS service
- Log on the official website of aliyun ;
- Move the mouse over the product tab , Click object storage OSS, open OSS Product details page ;
- stay OSS Product details page , Click open now .
Create storage space
-
Click the console button in the upper right corner of the webpage to enter the console
-
Choose object storage in my cloud products OSS
-
New storage space
-
Create a new storage space and set the read / write permission as public read
Four 、OSS Server side direct transmission
Introduce
Every OSS Of users will use the upload service .Web The common upload method is the user in the browser or App Upload files to the application server , The application server then uploads the file to OSS. The specific process is shown in the figure below .
And the data goes straight to OSS comparison , The above method has three disadvantages :
- Upload slow : User data needs to be uploaded to the application server first , And then upload it to OSS. Network transmission time is longer than direct transmission OSS Double . If the user data does not pass through the application server Server transfer , It goes straight to OSS, The speed will be greatly improved . and OSS use BGP bandwidth , It can guarantee the transmission speed between various operators .
- Expandability of : If there are more follow-up users , Application servers can become bottlenecks .
- The cost is high : Need to prepare multiple application servers . because OSS Upload traffic is free , If the data goes straight to OSS, Not through the application server , Then it will save a few application server .
Case process
Every OSS Of users will use the upload service .Web The common upload method is the user in the browser or App Upload files to the application server , The application server then uploads the file to OSS.
Add permissions to users
Then set the KeyID and KeySecret
Run the test and you can see the success in the cloud
The code can refer to the documents on the official website
Learn from the official website :https://help.aliyun.com/document_detail/32007.html
// Endpoint Take Chengdu for example , Other Region Please fill in according to the actual situation .
String endpoint = "http:// Their own bucket Address ";
// Cloud accounts AccessKey Have all API Access right , It is recommended to follow Alibaba cloud security best practices , Create and use RAM The sub account number is used for API Visit or daily operations , Please log in https://ram.console.aliyun.com establish .
// 1. establish RAM Sub account
// 2. get accessKeyId accessKeySecret
// 3. Set permissions for child users
String accessKeyId = " own accessKeyId ";
String accessKeySecret = " Their own accessKeySecret";
// establish OSSClient example .
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// Get current date , You can create a folder every day for management
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 OSSClient.
ossClient.shutdown();
System.out.println(" Upload successful !");
5、 ... and 、OSS Front end direct transmission - Back end signature
1. Introduce
Official website case
Web The client requests a signature from the server , Then upload it directly , No pressure on the server , And it's safe and reliable . However, the server in this example cannot know how many documents the user has uploaded in real time Pieces of , What files have been uploaded . If you want to know what files users uploaded in real time , You can use the server signature direct transmission and set the upload callback .
Process introduction
- Web The front end requests the application server , Get the parameters needed to upload ( Such as OSS Of accessKeyId、policy、callback Equal parameter )
- The application server returns the relevant parameters
- Web The front end goes directly to OSS The service initiates a file upload request
- When the upload is complete OSS The service will call back the callback interface of the application server ( Don't realize )
- The application server returns a response to OSS service ( Don't realize )
- OSS The service returns the contents of the application server callback interface to Web front end
2. Integrate OSS File upload
2.1 stay pom.xml Add related dependencies
<!--OSS SDK-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
2.2 Write a back end Controller 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 {
// Solve the cross domain annotation of the request
@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 bucketname .
String host = "https://" + bucket + "." + endpoint; // host The format is bucketname.endpoint
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String date = simpleDateFormat.format(new Date());
String dir = "tuling-test/"+date+"/"; // The prefix specified by the user when uploading the file .
// establish OSSClient example .
OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
try {
long expireTime = 30;
long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
Date expiration = new Date(expireEndTime);
// PostObject The maximum supported file size of the request is 5 GB, namely CONTENT_LENGTH_RANGE by 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"> Can only upload jpg/png file , And no more than 500kb</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; // Before uploading Sign the server return new Promise((resolve,reject)=>{
// Request backend this.axios.get('http://localhost:8088/oss/policy') // When using the arrow function this It 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 transmission OSS The server address of _self.objData.key=response.data.dir+"${filename}"; resolve(true); // Continue to upload }) .catch(function (error) {
console.log(error); reject(false) // Stop uploading }); }); } } } </script>
<style> </style>
版权声明
本文为[One duck, one duck]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230558023555.html
边栏推荐
- 【MySQL基础篇】启动选项与配置文件
- 2021年国产数据库12强介绍
- JS realizes modal box dragging
- 柯里化实现函数连续调用计算累加和
- 阅读笔记:FedGNN: Federated Graph Neural Network for Privacy-Preserving Recommendation
- 【Shell脚本练习】将新加的磁盘批量添加到指定的VG中
- Leak detection and vacancy filling (V)
- tc ebpf 实践
- 【代码解析(4)】Communication-Efficient Learning of Deep Networks from Decentralized Data
- rdma网络介绍
猜你喜欢
随机推荐
PHP 无限极分类和树形
DDOS攻击/防御介绍
leetcode刷题之二进制求和
2021-09-18
使用百度智能云人脸检测接口实现照片质量检测
初步认识Promse
页面缓存问题解决方法(慎用)
useCenterHook
【Shell脚本练习】将新加的磁盘批量添加到指定的VG中
Oracle Net Service:监听器与服务名解析方法
offset和client獲取dom元素比特置信息
openvswitch 编译安装
mysql密码过期的方法
LeetCode刷题|897递增顺序搜索树
Baidu map coordinates, Google coordinates and Tencent coordinates are mutually transformed
【代码解析(6)】Communication-Efficient Learning of Deep Networks from Decentralized Data
TP6 的 each 遍历用法
百度地图3D旋转和倾斜角度的调整
1-3 组件与模块
数据可视化进一步学习