通过COS上传文件至腾讯云

最近看了一下上传文件至腾讯云。腾讯官方提供的API,cloud.tencent.com/document/pr…

文档上传

文档上传首页要首先引入腾讯云封装好的cos-js-sdk-v5.js文件,然后再获取秘钥,签名可以是永久的也可以是临时的,由于密钥放在前端会暴露 SecretId 和 SecretKey,所以把永久密钥过程放在后端,前端通过发送一个ajax请求获取秘钥。

获取秘钥

// 初始化上传文档实例
this.cos = new Cos({ 
  getAuthorization: this.getDocSignature
})
// 获取上传文档签名
getDocSignature(options, callback) {
  const that = this
  $.ajax({
    url: '后台提供的请求地址', // 获取客户端上传签名的 URL
    type: 'GET',
    dataType: 'json',
    success(result) { // result 是派发签名服务器的回包
      if (result.code === statusCode.SUCCESS) {
        const fileKey = JSON.parse(result.data.fileKey).data
        callback({
          TmpSecretId: fileKey.credentials.tmpSecretId,
          TmpSecretKey: fileKey.credentials.tmpSecretKey,
          XCosSecurityToken: fileKey.credentials.sessionToken,
          ExpiredTime: fileKey.expiredTime
        })
      } else {
        // 获取秘钥失败的相关操作
      }
    }
  })
复制代码

开始上传

uploadDoc() { // 调取文档上传相关接口
  this.cos.sliceUploadFile({
    Bucket: '99999',  // 桶的名字,命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
    Region: '地区',   //Bucket所在的区域
    Key: this.fileObj.name,
    Body: this.fileObj, // 文件的信息
  }, (err, data) => {
    if (!err && data) {
      this.fileName = this.fileObj.name
      this.key = data.Key
      this.fileId = data.Key
      this.cos.getObjectUrl({ // 获取文件访问地址
        Method: 'PUT',
        Key: this.key,
        Bucket: 'aaa',
        Region: '地区',
        Sign: false
      }, (err, data) => {
        if (!err) { // 文档地址
          this.fileUrl = data.Url
        } else {
          this.$message.error('上传失败')
        }
      })
    } else {
      this.$message.error('上传失败')
    }
  })
},
复制代码

以上是文档的上传,视频的上传方式跟文档的上传要简单一些,这里就不多说了,大家有更好的方法或者其他的意见都可以提出来哈,我都会在第一时间回复!

转载于:https://juejin.im/post/5c2eb0b16fb9a049b506f242

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值