使用阿里雲OSS的服務端簽名后直傳功能


網站一般都會有上傳功能,而對象存儲服務oss是一個很好的選擇。可以快速的搭建起自己的上傳文件功能。
該文章以使用阿里雲的OSS功能為例,記錄如何在客戶端使用阿里雲的對象存儲服務。

服務端簽名后直傳

背景

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

流程介紹

流程如下圖所示:
image.png
本示例中,Web端向服務端請求簽名,然后直接上傳,不會對服務端產生壓力,而且安全可靠。但本示例中的服務端無法實時了解用戶上傳了多少文件,上傳了什么文件。如果想實時了解用戶上傳了什么文件,可以采用服務端簽名直傳並設置上傳回調。

創建對象存儲

1. 創建bucket

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

bucket讀寫權限為:公共讀

2. 添加子用戶分配權限

鼠標移至右上角的用戶頭像當中,點擊 添加AccessKey管理, 然后選擇使用子用戶AccessKey,因為使用子用戶可以只分配OSS的讀寫權限。這樣比較安全。
訪問方式選擇:編程訪問(即使用AccessKey ID 和 AccessKey Secret, 通過API或開發工具訪問)

然后點擊子用戶的添加權限操作。
權限選擇:AliyunOSSFullAccess(管理對象存儲服務(OSS)權限)
image.png

3.保存AccessKey信息

創建了用戶后,會展示這么一個頁面
image.png
此時你需要保存好AccessKeyID和AccessSecret,否則這個頁面關閉后就找不到了。

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的訪問權限,風險很高。強烈建議您創建並使用RAM賬號進行API訪問或日常運維,請登錄 https://ram.console.aliyun.com 創建RAM賬號。
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";

// 創建OSSClient實例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// 創建PutObjectRequest對象。
PutObjectRequest putObjectRequest = new PutObjectRequest("<yourBucketName>", "test", new File("C:\Users\82131\Desktop\logo.jpg"));

// 上傳文件。
ossClient.putObject(putObjectRequest);

// 關閉OSSClient。
ossClient.shutdown();   

image.png

測試成功后就可以看到test圖片了,如圖:
image.png

服務端簽名實現流程

修改CORS

客戶端進行表單直傳到OSS時,會從瀏覽器向OSS發送帶有Origin的請求消息。OSS對帶有Origin頭的請求消息會進行跨域規則(CORS)的驗證。因此需要為Bucket設置跨域規則以支持Post方法。
進入bucket后,選擇權限管理 -》跨域設置 -》創建規則
image.png

后端代碼

@RestController
public class OssController {

    @RequestMapping("/oss/policy")
    public Map<String, String> policy() {
        String accessId = "<yourAccessKeyId>"; // 請填寫您的AccessKeyId。
        String accessKey = "<yourAccessKeyId>"; // 請填寫您的AccessKeySecret。
        String endpoint = "oss-cn-shenzhen.aliyuncs.com"; // 請填寫您的 endpoint。
        String bucket = "bucket-name"; // 請填寫您的 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>();
        // 創建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#concept-ahk-rfz-2fb

前端代碼

以element-ui組件為例,上傳前BeforeUpload先調用后端的policy接口獲取簽名信息,然后帶着簽名等信息和圖片直接上傳到aliyun的OSS。
上傳組件singleUpload.vue,需要改動action的地址:bucket的外網域名(在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>

總結

該文主要由學習谷粒商城項目的實踐過程,技術難度並不大,阿里雲官網有文檔可以查閱。
快捷入口:https://help.aliyun.com/product/31815.html?spm=a2c4g.11186623.6.540.28c66d39lLTogx

個人博客網址: https://colablog.cn/

如果我的文章幫助到您,可以關注我的微信公眾號,第一時間分享文章給您
微信公眾號


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM