使用阿里云OSS的服務(wù)端簽名后直傳功能的流程分析
網(wǎng)站一般都會(huì)有上傳功能,而對(duì)象存儲(chǔ)服務(wù)oss是一個(gè)很好的選擇??梢钥焖俚拇罱ㄆ鹱约旱纳蟼魑募δ堋?br /> 該文章以使用阿里云的OSS功能為例,記錄如何在客戶(hù)端使用阿里云的對(duì)象存儲(chǔ)服務(wù)。
服務(wù)端簽名后直傳
背景
采用JavaScript客戶(hù)端直接簽名(參見(jiàn)JavaScript客戶(hù)端簽名直傳)時(shí),AccessKey ID和AcessKey Secret會(huì)暴露在前端頁(yè)面,因此存在嚴(yán)重的安全隱患。因此,OSS提供了服務(wù)端簽名后直傳的方案。
流程介紹
流程如下圖所示:

本示例中,Web端向服務(wù)端請(qǐng)求簽名,然后直接上傳,不會(huì)對(duì)服務(wù)端產(chǎn)生壓力,而且安全可靠。但本示例中的服務(wù)端無(wú)法實(shí)時(shí)了解用戶(hù)上傳了多少文件,上傳了什么文件。如果想實(shí)時(shí)了解用戶(hù)上傳了什么文件,可以采用服務(wù)端簽名直傳并設(shè)置上傳回調(diào)。
創(chuàng)建對(duì)象存儲(chǔ)
1. 創(chuàng)建bucket
快捷入口:https://oss.console.aliyun.com/bucket
bucket讀寫(xiě)權(quán)限為:公共讀
2. 添加子用戶(hù)分配權(quán)限
鼠標(biāo)移至右上角的用戶(hù)頭像當(dāng)中,點(diǎn)擊 添加AccessKey管理, 然后選擇使用子用戶(hù)AccessKey,因?yàn)槭褂米佑脩?hù)可以只分配OSS的讀寫(xiě)權(quán)限。這樣比較安全。
訪(fǎng)問(wèn)方式選擇:編程訪(fǎng)問(wèn)(即使用AccessKey ID 和 AccessKey Secret, 通過(guò)API或開(kāi)發(fā)工具訪(fǎng)問(wèn))
然后點(diǎn)擊子用戶(hù)的添加權(quán)限操作。
權(quán)限選擇:AliyunOSSFullAccess(管理對(duì)象存儲(chǔ)服務(wù)(OSS)權(quán)限)

3.保存AccessKey信息
創(chuàng)建了用戶(hù)后,會(huì)展示這么一個(gè)頁(yè)面

此時(shí)你需要保存好AccessKeyID和AccessSecret,否則這個(gè)頁(yè)面關(guān)閉后就找不到了。
maven依賴(lài)
<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
測(cè)試上傳
測(cè)試代碼
// Endpoint以杭州為例,其它Region請(qǐng)按實(shí)際情況填寫(xiě)。
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 阿里云主賬號(hào)AccessKey擁有所有API的訪(fǎng)問(wèn)權(quán)限,風(fēng)險(xiǎn)很高。強(qiáng)烈建議您創(chuàng)建并使用RAM賬號(hào)進(jìn)行API訪(fǎng)問(wèn)或日常運(yùn)維,請(qǐng)登錄 https://ram.console.aliyun.com 創(chuàng)建RAM賬號(hào)。
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
// 創(chuàng)建OSSClient實(shí)例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 創(chuàng)建PutObjectRequest對(duì)象。
PutObjectRequest putObjectRequest = new PutObjectRequest("<yourBucketName>", "test", new File("C:\Users\82131\Desktop\logo.jpg"));
// 上傳文件。
ossClient.putObject(putObjectRequest);
// 關(guān)閉OSSClient。
ossClient.shutdown();

測(cè)試成功后就可以看到test圖片了,如圖:

服務(wù)端簽名實(shí)現(xiàn)流程
修改CORS
客戶(hù)端進(jìn)行表單直傳到OSS時(shí),會(huì)從瀏覽器向OSS發(fā)送帶有Origin的請(qǐng)求消息。OSS對(duì)帶有Origin頭的請(qǐng)求消息會(huì)進(jìn)行跨域規(guī)則(CORS)的驗(yàn)證。因此需要為Bucket設(shè)置跨域規(guī)則以支持Post方法。
進(jìn)入bucket后,選擇權(quán)限管理 -》跨域設(shè)置 -》創(chuàng)建規(guī)則

后端代碼
@RestController
public class OssController {
@RequestMapping("/oss/policy")
public Map<String, String> policy() {
String accessId = "<yourAccessKeyId>"; // 請(qǐng)?zhí)顚?xiě)您的AccessKeyId。
String accessKey = "<yourAccessKeyId>"; // 請(qǐng)?zhí)顚?xiě)您的AccessKeySecret。
String endpoint = "oss-cn-shenzhen.aliyuncs.com"; // 請(qǐng)?zhí)顚?xiě)您的 endpoint。
String bucket = "bucket-name"; // 請(qǐng)?zhí)顚?xiě)您的 bucketname 。
String host = "https://" + bucket + "." + endpoint; // host的格式為 bucketname.endpoint
String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String dir = format + "/"; // 用戶(hù)上傳文件時(shí)指定的前綴。
Map<String, String> respMap = new LinkedHashMap<String, String>();
// 創(chuàng)建OSSClient實(shí)例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
try {
long expireTime = 30;
long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
Date expiration = new Date(expireEndTime);
// PostObject請(qǐng)求最大可支持的文件大小為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;
}
}
更詳細(xì)的詳細(xì)請(qǐng)查看這里:https://help.aliyun.com/document_detail/91868.html?spm=a2c4g.11186623.2.15.a66e6e28WZXmSg
前端代碼
以element-ui組件為例,上傳前BeforeUpload先調(diào)用后端的policy接口獲取簽名信息,然后帶著簽名等信息和圖片直接上傳到aliyun的OSS。
上傳組件singleUpload.vue,需要改動(dòng)action的地址:bucket的外網(wǎng)域名(在bucket的概覽里面可以看到),該文件是谷粒商城項(xiàng)目的一個(gè)上傳組件,我只是copy過(guò)來(lái)修改了一點(diǎn)點(diǎn)。
<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">點(diǎn)擊上傳</el-button>
<div slot="tip" class="el-upload__tip">只能上傳jpg/png文件,且不超過(guò)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異步請(qǐng)求獲取簽名信息
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組件的頁(yè)面的示例代碼:
<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í)谷粒商城項(xiàng)目的實(shí)踐過(guò)程,技術(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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中Vector與ArrayList的區(qū)別詳解
本篇文章是對(duì)Java中Vector與ArrayList的區(qū)別進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06
Java?SE使用for?each循環(huán)遍歷數(shù)組的方法代碼
在Java?SE開(kāi)發(fā)中,數(shù)組是最常見(jiàn)的數(shù)據(jù)結(jié)構(gòu)之一,Java提供了多種遍歷數(shù)組的方式,其中for循環(huán)是最常用的方式之一,本文將介紹如何使用for?each循環(huán)遍歷數(shù)組,接下來(lái),我們將通過(guò)一個(gè)簡(jiǎn)單的代碼示例來(lái)展示如何使用for?each循環(huán)遍歷數(shù)組,需要的朋友可以參考下2023-11-11
Java調(diào)用HTTPS接口實(shí)現(xiàn)繞過(guò)SSL認(rèn)證
SSL認(rèn)證是確保通信安全的重要手段,有的時(shí)候?yàn)榱朔奖阏{(diào)用,我們會(huì)繞過(guò)SSL認(rèn)證,這篇文章主要介紹了Java如何調(diào)用HTTPS接口實(shí)現(xiàn)繞過(guò)SSL認(rèn)證,需要的可以參考下2023-11-11
JavaCV調(diào)用百度AI實(shí)現(xiàn)人臉檢測(cè)方法詳解
在檢測(cè)人臉數(shù)量、位置、性別、口罩等場(chǎng)景時(shí),可以考慮使用百度開(kāi)放平臺(tái)提供的web接口,一個(gè)web請(qǐng)求就能完成檢測(cè)得到結(jié)果。本文就為大家介紹JavaCV如何調(diào)用百度AI實(shí)現(xiàn)最簡(jiǎn)單的人臉檢測(cè),需要的可以參考一下2022-01-01
java實(shí)現(xiàn)ftp上傳 如何創(chuàng)建文件夾
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)ftp上傳的相關(guān)資料,教大家如何創(chuàng)建文件夾?具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04
springboot統(tǒng)一返回json數(shù)據(jù)格式并配置系統(tǒng)異常攔截方式
這篇文章主要介紹了springboot統(tǒng)一返回json數(shù)據(jù)格式并配置系統(tǒng)異常攔截方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08
2022版IDEA創(chuàng)建一個(gè)maven項(xiàng)目的超詳細(xì)圖文教程
IDEA是用于java語(yǔ)言開(kāi)發(fā)的集成環(huán)境,并且經(jīng)常用于maven、spring、MyBatis等項(xiàng)目的開(kāi)發(fā),下面這篇文章主要給大家介紹了關(guān)于2022版IDEA創(chuàng)建一個(gè)maven項(xiàng)目的超詳細(xì)圖文教程,需要的朋友可以參考下2023-02-02

