基于element ui 实现七牛云自定义key上传文件,并监听更新上传进度
借助上传Upload 上传组件的 http-request 覆盖默认的上传行为,可以自定义上传的实现
<el-upload multiple ref="sliderUpload" :data="uploadData" :action="uploadData.url" list-type="picture-card" accept="image/png,image/jpeg,image/jpg" :auto-upload="true" :limit="numberLimit.slider" :file-list="sliderList" :http-request="sliderRequest" :before-upload="beforeUpload" :on-remove="sliderRemove" :on-preview="picturePreview" :on-error="uploadError" :on-exceed="uploadLimit"> <i class="el-icon-plus"></i> <div class="el-upload__tip" slot="tip">限上传9张轮播图</div> </el-upload>
sliderRequest(upload) { // 文件上传自行处理上传 // 创建FormData对象 添加相关上传参数 const formData = new FormData() // 文件对象 formData.append('file', upload.file) // key 文件名处理 images/时间戳_随机字符串.文件后缀 formData.append('key', `images/${new Date().getTime()}_${randomString()}.${upload.file.name.substring(upload.file.name.lastIndexOf('.') + 1)}`) // token formData.append('token', this.uploadData.token) // 上传文件 // onUploadProgress 查看axios文档 https://github.com/axios/axios axios.post(this.uploadData.url, formData, { onUploadProgress: (event) => { // 监听上传进度 event.percent = event.loaded / event.total * 100 upload.onProgress(event) } }).then((response) => { const res = response.data if (res.code === 200) { // 调用组件上传成功方法 upload.onSuccess() // 轮播图上传成功 这里做相关逻辑this.$message.success('上传成功') } }).catch((err) => { // 调用组件上传失败方法 upload.onError() this.$message.error('上传失败,' + err) }) }