使用阿里云OSS的服務(wù)端簽名后直傳功能的流程分析
網(wǎng)站一般都會有上傳功能,而對象存儲服務(wù)oss是一個很好的選擇??梢钥焖俚拇罱ㄆ鹱约旱纳蟼魑募δ堋?br /> 該文章以使用阿里云的OSS功能為例,記錄如何在客戶端使用阿里云的對象存儲服務(wù)。
服務(wù)端簽名后直傳
背景
采用JavaScript客戶端直接簽名(參見JavaScript客戶端簽名直傳)時,AccessKey ID和AcessKey Secret會暴露在前端頁面,因此存在嚴重的安全隱患。因此,OSS提供了服務(wù)端簽名后直傳的方案。
流程介紹
流程如下圖所示:
本示例中,Web端向服務(wù)端請求簽名,然后直接上傳,不會對服務(wù)端產(chǎn)生壓力,而且安全可靠。但本示例中的服務(wù)端無法實時了解用戶上傳了多少文件,上傳了什么文件。如果想實時了解用戶上傳了什么文件,可以采用服務(wù)端簽名直傳并設(shè)置上傳回調(diào)。
創(chuàng)建對象存儲
1. 創(chuàng)建bucket
快捷入口:https://oss.console.aliyun.com/bucket
bucket讀寫權(quán)限為:公共讀
2. 添加子用戶分配權(quán)限
鼠標移至右上角的用戶頭像當(dāng)中,點擊 添加AccessKey管理, 然后選擇使用子用戶AccessKey,因為使用子用戶可以只分配OSS的讀寫權(quán)限。這樣比較安全。
訪問方式選擇:編程訪問(即使用AccessKey ID 和 AccessKey Secret, 通過API或開發(fā)工具訪問)
然后點擊子用戶的添加權(quán)限操作。
權(quán)限選擇:AliyunOSSFullAccess(管理對象存儲服務(wù)(OSS)權(quán)限)
3.保存AccessKey信息
創(chuàng)建了用戶后,會展示這么一個頁面
此時你需要保存好AccessKeyID和AccessSecret,否則這個頁面關(guān)閉后就找不到了。
maven依賴
<dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.10.2</version> </dependency>
最新版本可以看這里:https://help.aliyun.com/document_detail/32009.html?spm=a2c4g.11186623.6.807.39fb4c07GmTHoV
測試上傳
測試代碼
// Endpoint以杭州為例,其它Region請按實際情況填寫。 String endpoint = "http://oss-cn-hangzhou.aliyuncs.com"; // 阿里云主賬號AccessKey擁有所有API的訪問權(quán)限,風(fēng)險很高。強烈建議您創(chuàng)建并使用RAM賬號進行API訪問或日常運維,請登錄 https://ram.console.aliyun.com 創(chuàng)建RAM賬號。 String accessKeyId = "<yourAccessKeyId>"; String accessKeySecret = "<yourAccessKeySecret>"; // 創(chuàng)建OSSClient實例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 創(chuàng)建PutObjectRequest對象。 PutObjectRequest putObjectRequest = new PutObjectRequest("<yourBucketName>", "test", new File("C:\Users\82131\Desktop\logo.jpg")); // 上傳文件。 ossClient.putObject(putObjectRequest); // 關(guān)閉OSSClient。 ossClient.shutdown();
測試成功后就可以看到test圖片了,如圖:
服務(wù)端簽名實現(xiàn)流程
修改CORS
客戶端進行表單直傳到OSS時,會從瀏覽器向OSS發(fā)送帶有Origin的請求消息。OSS對帶有Origin頭的請求消息會進行跨域規(guī)則(CORS)的驗證。因此需要為Bucket設(shè)置跨域規(guī)則以支持Post方法。
進入bucket后,選擇權(quán)限管理 -》跨域設(shè)置 -》創(chuàng)建規(guī)則
后端代碼
@RestController public class OssController { @RequestMapping("/oss/policy") public Map<String, String> policy() { String accessId = "<yourAccessKeyId>"; // 請?zhí)顚懩腁ccessKeyId。 String accessKey = "<yourAccessKeyId>"; // 請?zhí)顚懩腁ccessKeySecret。 String endpoint = "oss-cn-shenzhen.aliyuncs.com"; // 請?zhí)顚懩?endpoint。 String bucket = "bucket-name"; // 請?zhí)顚懩?bucketname 。 String host = "https://" + bucket + "." + endpoint; // host的格式為 bucketname.endpoint String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); String dir = format + "/"; // 用戶上傳文件時指定的前綴。 Map<String, String> respMap = new LinkedHashMap<String, String>(); // 創(chuàng)建OSSClient實例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey); try { long expireTime = 30; long expireEndTime = System.currentTimeMillis() + expireTime * 1000; Date expiration = new Date(expireEndTime); // PostObject請求最大可支持的文件大小為5 GB,即CONTENT_LENGTH_RANGE為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); 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)); } catch (Exception e) { // Assert.fail(e.getMessage()); System.out.println(e.getMessage()); } finally { ossClient.shutdown(); } return respMap; } }
更詳細的詳細請查看這里:https://help.aliyun.com/document_detail/91868.html?spm=a2c4g.11186623.2.15.a66e6e28WZXmSg
前端代碼
以element-ui組件為例,上傳前BeforeUpload先調(diào)用后端的policy接口獲取簽名信息,然后帶著簽名等信息和圖片直接上傳到aliyun的OSS。
上傳組件singleUpload.vue,需要改動action的地址:bucket的外網(wǎng)域名(在bucket的概覽里面可以看到),該文件是谷粒商城項目的一個上傳組件,我只是copy過來修改了一點點。
<template> <div> <el-upload action="http://colablog.oss-cn-shenzhen.aliyuncs.com" :data="dataObj" list-type="picture" :multiple="false" :show-file-list="showFileList" :file-list="fileList" :before-upload="beforeUpload" :on-remove="handleRemove" :on-success="handleUploadSuccess" :on-preview="handlePreview" > <el-button size="small" type="primary">點擊上傳</el-button> <div slot="tip" class="el-upload__tip">只能上傳jpg/png文件,且不超過10MB</div> </el-upload> <el-dialog :visible.sync="dialogVisible"> <img width="100%" :src="fileList[0].url" alt=""> </el-dialog> </div> </template> <script> export default { name: 'SingleUpload', props: { value: String }, data() { return { dataObj: { policy: '', signature: '', key: '', ossaccessKeyId: '', dir: '', host: '' // callback:'', }, dialogVisible: false } }, computed: { imageUrl() { return this.value }, imageName() { if (this.value != null && this.value !== '') { return this.value.substr(this.value.lastIndexOf('/') + 1) } else { return null } }, fileList() { return [{ name: this.imageName, url: this.imageUrl }] }, showFileList: { get: function() { return this.value !== null && this.value !== '' && this.value !== undefined }, set: function(newValue) { } } }, methods: { emitInput(val) { this.$emit('input', val) }, handleRemove(file, fileList) { this.emitInput('') }, handlePreview(file) { this.dialogVisible = true }, getUUID() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => { return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16) }) }, beforeUpload(file) { const _self = this return new Promise((resolve, reject) => { // 前后端提交post異步請求獲取簽名信息 this.postRequest('/oss/policy') .then((response) => { _self.dataObj.policy = response.policy _self.dataObj.signature = response.signature _self.dataObj.ossaccessKeyId = response.accessid _self.dataObj.key = response.dir + this.getUUID() + '_${filename}' _self.dataObj.dir = response.dir _self.dataObj.host = response.host resolve(true) }).catch(err => { reject(false) }) }) }, handleUploadSuccess(res, file) { console.log('上傳成功...') this.showFileList = true this.fileList.pop() this.fileList.push({ name: file.name, url: this.dataObj.host + '/' + this.dataObj.key.replace('${filename}', file.name) }) this.emitInput(this.fileList[0].url) } } } </script>
引用SingleUpload組件的頁面的示例代碼:
<template> <div> <el-form :model="admin" label-width="60px"> <el-form-item label="頭像"> <single-upload v-model="admin.userImg" /> </el-form-item> </el-form> </div> </template> <script> import singleUpload from '@/components/upload/singleUpload' export default { components: { singleUpload }, data() { return { admin: { userImg: '' } } } } </script>
總結(jié)
該文主要由學(xué)習(xí)谷粒商城項目的實踐過程,技術(shù)難度并不大,阿里云官網(wǎng)有文檔可以查閱。
快捷入口:[https://help.aliyun.com/product/31815.html?spm=a2c4g.11186623.6.540.28c66d39lLTogx]https://help.aliyun.com/product/31815.html?spm=a2c4g.11186623.6.540.28c66d39lLTogx
到此這篇關(guān)于使用阿里云OSS的服務(wù)端簽名后直傳功能的文章就介紹到這了,更多相關(guān)服務(wù)端簽名后直傳內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中Vector與ArrayList的區(qū)別詳解
本篇文章是對Java中Vector與ArrayList的區(qū)別進行了詳細的分析介紹,需要的朋友參考下2013-06-06Java?SE使用for?each循環(huán)遍歷數(shù)組的方法代碼
在Java?SE開發(fā)中,數(shù)組是最常見的數(shù)據(jù)結(jié)構(gòu)之一,Java提供了多種遍歷數(shù)組的方式,其中for循環(huán)是最常用的方式之一,本文將介紹如何使用for?each循環(huán)遍歷數(shù)組,接下來,我們將通過一個簡單的代碼示例來展示如何使用for?each循環(huán)遍歷數(shù)組,需要的朋友可以參考下2023-11-11Java調(diào)用HTTPS接口實現(xiàn)繞過SSL認證
SSL認證是確保通信安全的重要手段,有的時候為了方便調(diào)用,我們會繞過SSL認證,這篇文章主要介紹了Java如何調(diào)用HTTPS接口實現(xiàn)繞過SSL認證,需要的可以參考下2023-11-11JavaCV調(diào)用百度AI實現(xiàn)人臉檢測方法詳解
在檢測人臉數(shù)量、位置、性別、口罩等場景時,可以考慮使用百度開放平臺提供的web接口,一個web請求就能完成檢測得到結(jié)果。本文就為大家介紹JavaCV如何調(diào)用百度AI實現(xiàn)最簡單的人臉檢測,需要的可以參考一下2022-01-01java實現(xiàn)ftp上傳 如何創(chuàng)建文件夾
這篇文章主要為大家詳細介紹了java實現(xiàn)ftp上傳的相關(guān)資料,教大家如何創(chuàng)建文件夾?具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04springboot統(tǒng)一返回json數(shù)據(jù)格式并配置系統(tǒng)異常攔截方式
這篇文章主要介紹了springboot統(tǒng)一返回json數(shù)據(jù)格式并配置系統(tǒng)異常攔截方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-082022版IDEA創(chuàng)建一個maven項目的超詳細圖文教程
IDEA是用于java語言開發(fā)的集成環(huán)境,并且經(jīng)常用于maven、spring、MyBatis等項目的開發(fā),下面這篇文章主要給大家介紹了關(guān)于2022版IDEA創(chuàng)建一個maven項目的超詳細圖文教程,需要的朋友可以參考下2023-02-02