上传文件到阿里云

1.引入阿里云

import OSS from 'ali-oss'

2.利用input的file属性选择上传的文件

const file = e.target.files[0]
e.target.value = ''

注:选择文件时使用accept属性会导致一部分手机无法正常的上传文件,可以使用file.type判断文件的类型

3.调取后端接口,获取上传阿里云的参数

ossParams().then(res => {
          const client = new OSS.Wrapper({
          accessKeyId: res.data.accessKeyId,
          accessKeySecret: res.data.accessKeySecret,
          bucket: res.data.bucket,
          endpoint: res.data.endpoint,
          region: res.data.region,
          secure: true
        })

4.随机定义文件的名称

let randomName = that.random_string()
random_string (len) {    //定义在上传文件之外的方法
      len = len || 32
      var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
      var maxPos = chars.length
      var pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    }

5.设置上传的进度

const progress = function (p) {
        return function (done) {
          that.percentage = Math.floor(p * 100)
          done()
        }
      }

6.开始进行上传(放在阿里云的abc文件夹下)

client.multipartUpload('abc/' + randomName, file, { progress: progress }).then(function (result) {
          // console.log(result)
          that.vedioUrl = result.res.requestUrls[0].split('?uploadId=')[0]
          that.$message({
            message: '上传成功',
            type: 'success'
          })
        }).catch(() => {
          that.$message({
            message: '上传失败',
            type: 'error'
          })
        })
 
 

猜你喜欢

转载自blog.csdn.net/lemon_bubbly/article/details/80227939
今日推荐