Browser上传文件到华为云/七牛云 详细步骤

一、华为云(OBS BrowserJS)

华为云上传示例:跳转链接

参考 链接

 

 

 

1、华为云开通OBS对象存储,建议使用后端生成签名认证方式上传,调取接口来进行获取key和token。

 

 

 2、下载SDK BrowserJS (esdk-obs-browserjs  3.20.7  )

使用npm引入即可,下载下来的node_modules里

yarn add esdk-obs-browserjs 

 也可以将上图的js文件保存在本地文件夹中进行引用。

3、vue文件中引入,进行上传

import ObsClient from 'esdk-obs-browserjs'

upload (file) {
      const that = this
      const bucketName = 'xxx-bucket' // 桶名
      const serverUrl = 'xxxxx.myhuaweicloud.com' // 服务器地址
      this.importLoading = true
      // 后端生成秘钥,调取接口进行获取
      getHuaweiProvisionalSecurityKeyCloud().then(res => {
        console.log(file.name, res)
        var obsClient = new ObsClient({
          access_key_id: res.data.access,
          secret_access_key: res.data.secret,
          security_token: res.data.securitytoken,
          server: serverUrl
        })
        obsClient.putObject({
          Bucket: bucketName,  // 桶名
          Key: file.name,
          SourceFile: file,
          ContentType: 'text/plain'
        }, function (err, result) {
          if (err) {
            console.error('Error-->' + err)
            that.$notification.error({
              message: '上传失败,请重试'
            })
          } else {
            if (result.CommonMsg.Status < 300) {
             // 上传成功后,文件地址
              const fileUrl = 'https://' + bucketName + '.' + serverUrl + '/' + file.name
              that.$notification.success({
                message: '文件上传成功!'
              })
            } else {
              that.$notification.error({
                message: '上传失败,请重试'
              })
              console.log('Code-->' + result.CommonMsg.Code)
              console.log('Message-->' + result.CommonMsg.Message)
            }
          }
        })
      }).catch(() => {
        // catch
      })
    },

 

二、七牛云()

参考七牛官方文档 跳转链接

1、跟华为云类似,同样需要后端生成token和key,前端进行获取。

2、引入qiniu-js

yarn add qiniu-js

3、vue文件中引入,进行上传

import * as qiniu from 'qiniu-js'


beforeUploadVideo (file) {
   // 获取秘钥token
  getQiniuToken().then(res => {
    const token = res.data.token
    const key = file.name
    const observable = qiniu.upload(file, key, token)
    observable.subscribe(next => {
      console.log('next', next)
    }, error => {
      console.log('error', error)
    }, complete => {
      this.url = res.data.domain + complete.key
      console.log('complete-url', res.data.domain + complete.key)
    })
  })
}

 

posted @ 2021-08-26 18:02  辰熙ali  阅读(1004)  评论(0编辑  收藏  举报