騰訊雲cos對象存儲使用方法


相關文檔

零時密鑰生成指引:https://cloud.tencent.com/document/product/436/14048

node.js SDK文檔:https://cloud.tencent.com/document/product/436/8629

javascript SDK文檔:https://cloud.tencent.com/document/product/436/7751

cos對象存儲API文檔:https://cloud.tencent.com/document/product/436/7751

前端web上傳官方demo: https://github.com/tencentyun/cos-snippets/tree/master/JavaScript

web端上傳(操作)文件

官方介紹的方式有4種,這里以第1種和第4種做簡單說明。

第一種方法

這種方法需要通過web端請求服務端接口獲取臨時密鑰,通過調用服務端接口獲取臨時密鑰,用臨時密鑰new一個cos實例。用cos實例上的方法來上傳或操作文件。

首先需要安裝官方提供的SDK包 npm i cos-js-sdk-v5 --save

demo如下:

// 前端代碼

import React from 'react'
import COS from 'cos-js-sdk-v5'
import config from '../../../../config/index.json'

// 用於發送請求
function ajax(method, url, data = null) {
  return new Promise(resolve => {
    const xhr = new XMLHttpRequest()
    xhr.open(method, url, false)
    xhr.onload = () => {
      const result = JSON.parse(xhr.responseText)
      resolve(result)
    }
    xhr.send(data)
  })
}

// 生成cos實例
const cos = new COS({
  // 必選參數
  getAuthorization: async function (options, callback) {
    // 請求的URL替換為服務端提供的接口
    const data = await ajax('GET', 'http://127.0.0.1:8000/sts')
    console.log('臨時密鑰:', data)
    var credentials = data && data.credentials;
    if (!data || !credentials) return console.error('credentials invalid');
    callback({
      TmpSecretId: credentials.tmpSecretId,
      TmpSecretKey: credentials.tmpSecretKey,
      XCosSecurityToken: credentials.sessionToken,
      // 建議返回服務器時間作為簽名的開始時間,避免用戶瀏覽器本地時間偏差過大導致簽名錯誤
      StartTime: data.startTime, // 時間戳,單位秒,如:1580000000
      ExpiredTime: data.expiredTime, // 時間戳,單位秒,如:1580000900
    })
  }
})

function App() {
  const uploadCos = (file, filename) => {
    cos.putObject({
      Bucket: config.Bucket,     /* 必須 */
      Region: config.Region,     /* 存儲桶所在地域,必須字段 */
      Key: filename,              /* 必須 */
      StorageClass: 'STANDARD',
      Body: file, // 上傳文件對象
      onProgress: function (progressData) {
        console.log('progress', JSON.stringify(progressData));
      }
    }, function (err, data) {
      console.log('msg:', err || data);
    });
  }

  const uploadHandle = () => (
    new Promise(resolve => {
      const int = document.createElement('input')
      int.type = 'file'
      int.click()
      int.onchange = () => {
        const file = int.files[0]
        console.log('file:', file)
        resolve(file)
      }
    })
  )

  const onUpload = async () => {
    const file = await uploadHandle()
    uploadCos(file, file.name)
  }
  return <button onClick={onUpload}>點擊上傳</button>
}

export default App

nodejs服務端代碼(生成臨時密鑰)

安裝依賴包: npm i express cors qcloud-cos-sts --save

const app = require('express')()
const cors = require('cors')
const STS = require('qcloud-cos-sts') // 用於生成零時密鑰

// 配置參數
const config = {
  secretId: configs.SecretId,   // 替換你的固定密鑰
  secretKey: configs.SecretKey,  //替換你的固定密鑰
  proxy: '',
  durationSeconds: 1800,  // 密鑰有效期
  // 放行判斷相關參數
  bucket: configs.Bucket, // 換成你的 bucket
  region: configs.Region, // 換成 bucket 所在地區
  allowPrefix: '*', // 這里改成允許的路徑前綴,可以根據自己網站的用戶登錄態判斷允許上傳的具體路徑,例子: a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全風險, 請謹慎評估使用)
  allowActions: [
    // 所有 action 請看文檔 https://cloud.tencent.com/document/product/436/31923
    // 簡單上傳
    'name/cos:PutObject',
    'name/cos:PostObject',
    // 分片上傳
    'name/cos:InitiateMultipartUpload',
    'name/cos:ListMultipartUploads',
    'name/cos:ListParts',
    'name/cos:UploadPart',
    'name/cos:CompleteMultipartUpload'
  ],
};

// 處理跨域
app.use(cors())

// 生成臨時密鑰接口
app.get('/sts', (req, res) => {
  // 獲取臨時密鑰
  var shortBucketName = config.bucket.substr(0, config.bucket.lastIndexOf('-'));
  var appId = config.bucket.substr(1 + config.bucket.lastIndexOf('-'));
  var policy = {
    'version': '2.0',
    'statement': [{
      'action': config.allowActions,
      'effect': 'allow',
      'principal': { 'qcs': ['*'] },
      'resource': [
        'qcs::cos:' + config.region + ':uid/' + appId + ':prefix//' + appId + '/' + shortBucketName + '/' + config.allowPrefix,
      ],
    }],
  };
  STS.getCredential({
    secretId: config.secretId,
    secretKey: config.secretKey,
    proxy: config.proxy,
    durationSeconds: config.durationSeconds,
    policy: policy,
  }, function (err, tempKeys) {
    var result = JSON.stringify(err || tempKeys) || '';
    res.send(result);
  });
})

app.listen(8000)
console.log(`server running at: http://localhost:8000`)

第二種方法

第二種方法使用比較簡單,不需要依賴服務端生成臨時密鑰。由於密鑰保存在前端不安全,僅用於測試時使用。

demo:

import COS from 'cos-js-sdk-v5'

 const cos = new COS({
  SecretId: config.SecretId, // 替換你的SecretId
  SecretKey: config.SecretKey, // 替換你的SecretKey
})

cos.putObject({
  Bucket: config.Bucket,     /* 必須  替換你的Bucket */
  Region: config.Region,     /* 存儲桶所在地域,必須字段 替換你的Region */
  Key: filename,              /* 必須 */
  StorageClass: 'STANDARD',
  Body: file, // 上傳文件對象
  onProgress: function (progressData) {
    console.log('progress', JSON.stringify(progressData));
  }
}, function (err, data) {
  console.log('msg:', err || data);
});


免責聲明!

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



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