美文网首页Vue.jsVue
vue 上传文件到 阿里云OSS,并获取上传进度

vue 上传文件到 阿里云OSS,并获取上传进度

作者: 东京的雨不会淋湿首尔 | 来源:发表于2018-11-03 17:02 被阅读12次

1.首先,安装阿里的包

npm install ali-oss

初始化一下配置,传的参数data从后台获取

const OSS = require('ali-oss')

export function client(data) {
    //后端提供数据
  return new OSS({
    region: data.region,  //oss-cn-shenzhen.aliyuncs.com
    accessKeyId: data.accessKeyId,
    accessKeySecret: data.accessKeySecret,
    bucket: data.bucket
  })
}

2.使用element-ui的Upload作为上传组件,http-request 来绑定自定义上传的方法Upload,action写为空。 :before-upload="beforeUpload" 表示在上传前做的事情,绑定了方法beforeUpload,我们可以在这个方法里获取所需要的一些信息,比如签名等等

<el-upload
      :http-request="Upload"
      :data="dataObj" 
      :multiple="false"
      :show-file-list="false"
      :before-upload="beforeUpload" //在上传前做的事情
      class="image-uploader"
      drag
      action=""
    >
      <i class="el-icon-upload"/>
      <div class="el-upload__text">将图片拖到此处,或<em>点击上传</em></div>
    </el-upload>

data 例子如下

data() {
      return {
        tempUrl: '', //存上传后的图片url
        dataObj: {}, //存签名信息
        baseAli: 'oss-cn-shenzhen.aliyuncs.com', //后面连接图片url用的,根据自己aili OSS 配制修改
      progress:0//进度条
      }
    },

3.methods
从后台获取第一步所需的数据


  beforeUpload() {
        return new Promise((resolve, reject) => {
//从后台获取第一步所需的数据
          getAliToken().then(response => {
            this.dataObj = response.data
            resolve(true)
          }).catch(err => {
            console.log(err)
            reject(false)
          })
        })
      },

上传方法

Upload(file) {
        const that = this
        //判断扩展名
        const tmpcnt = file.file.name.lastIndexOf(".")
        const exname = file.file.name.substring(tmpcnt + 1)
        const names = ['jpg', 'jpeg', 'webp', 'png','bmp']
        if(names.indexOf(exname)< 0 ){
          this.$message.error("不支持的格式!")
          return
        }
        async function multipartUpload () {

          const fileName = that.name + file.file.uid
          //定义唯一的文件名,打印出来的uid其实就是时间戳
          //client 是第一步中的 client
          client(that.dataObj).multipartUpload(fileName, file.file,
            {
              progress:function (p) { //获取进度条的值
                console.log(p)
                that.progress = p*100
              },

            }).then(
            result => {
              //下面是如果对返回结果再进行处理,根据项目需要
              // console.log(result)
              that.tempUrl = 'http://'+result.bucket+'.'+that.baseAli+ '/' + result.name

            }).catch(err => {
            console.log("err:",err)
          })
        }
        multipartUpload ()


      },

至此,上传完成

相关文章

网友评论

    本文标题:vue 上传文件到 阿里云OSS,并获取上传进度

    本文链接:https://www.haomeiwen.com/subject/bunkxqtx.html