溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

使用阿里云OSS的服務(wù)端簽名后直傳功能的方法

發(fā)布時(shí)間:2020-11-03 17:59:23 來源:億速云 閱讀:525 作者:Leah 欄目:開發(fā)技術(shù)

本篇文章為大家展示了使用阿里云OSS的服務(wù)端簽名后直傳功能的方法,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

服務(wù)端簽名后直傳

背景

采用JavaScript客戶端直接簽名(參見JavaScript客戶端簽名直傳)時(shí),AccessKey ID和AcessKey Secret會(huì)暴露在前端頁(yè)面,因此存在嚴(yán)重的安全隱患。因此,OSS提供了服務(wù)端簽名后直傳的方案。

流程介紹

流程如下圖所示:

使用阿里云OSS的服務(wù)端簽名后直傳功能的方法

本示例中,Web端向服務(wù)端請(qǐng)求簽名,然后直接上傳,不會(huì)對(duì)服務(wù)端產(chǎn)生壓力,而且安全可靠。但本示例中的服務(wù)端無法實(shí)時(shí)了解用戶上傳了多少文件,上傳了什么文件。如果想實(shí)時(shí)了解用戶上傳了什么文件,可以采用服務(wù)端簽名直傳并設(shè)置上傳回調(diào)。

創(chuàng)建對(duì)象存儲(chǔ)

1. 創(chuàng)建bucket

快捷入口:https://oss.console.aliyun.com/bucket

bucket讀寫權(quán)限為:公共讀

2. 添加子用戶分配權(quán)限

鼠標(biāo)移至右上角的用戶頭像當(dāng)中,點(diǎn)擊 添加AccessKey管理, 然后選擇使用子用戶AccessKey,因?yàn)槭褂米佑脩艨梢灾环峙銸SS的讀寫權(quán)限。這樣比較安全。
訪問方式選擇:編程訪問(即使用AccessKey ID 和 AccessKey Secret, 通過API或開發(fā)工具訪問)

然后點(diǎn)擊子用戶的添加權(quán)限操作。
權(quán)限選擇:AliyunOSSFullAccess(管理對(duì)象存儲(chǔ)服務(wù)(OSS)權(quán)限)

使用阿里云OSS的服務(wù)端簽名后直傳功能的方法

3.保存AccessKey信息

創(chuàng)建了用戶后,會(huì)展示這么一個(gè)頁(yè)面

使用阿里云OSS的服務(wù)端簽名后直傳功能的方法

此時(shí)你需要保存好AccessKeyID和AccessSecret,否則這個(gè)頁(yè)面關(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&#63;spm=a2c4g.11186623.6.807.39fb4c07GmTHoV

測(cè)試上傳

測(cè)試代碼

// Endpoint以杭州為例,其它Region請(qǐng)按實(shí)際情況填寫。
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 阿里云主賬號(hào)AccessKey擁有所有API的訪問權(quán)限,風(fēng)險(xiǎn)很高。強(qiáng)烈建議您創(chuàng)建并使用RAM賬號(hào)進(jìn)行API訪問或日常運(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(); 

使用阿里云OSS的服務(wù)端簽名后直傳功能的方法

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

使用阿里云OSS的服務(wù)端簽名后直傳功能的方法

服務(wù)端簽名實(shí)現(xiàn)流程

修改CORS

客戶端進(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ī)則

使用阿里云OSS的服務(wù)端簽名后直傳功能的方法

后端代碼

@RestController
public class OssController {

 @RequestMapping("/oss/policy")
 public Map<String, String> policy() {
  String accessId = "<yourAccessKeyId>"; // 請(qǐng)?zhí)顚懩腁ccessKeyId。
  String accessKey = "<yourAccessKeyId>"; // 請(qǐng)?zhí)顚懩腁ccessKeySecret。
  String endpoint = "oss-cn-shenzhen.aliyuncs.com"; // 請(qǐng)?zhí)顚懩?endpoint。
  String bucket = "bucket-name"; // 請(qǐng)?zhí)顚懩?bucketname 。
  String host = "https://" + bucket + "." + endpoint; // host的格式為 bucketname.endpoint

  String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
  String dir = format + "/"; // 用戶上傳文件時(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&#63;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過來修改了一點(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文件,且不超過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' &#63; (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>

上述內(nèi)容就是使用阿里云OSS的服務(wù)端簽名后直傳功能的方法,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI