问题: 使用el-upload上传多文件时,on-success钩子只拿到了一个response,上传只成功上传了一个。
解决:使用:http-requst来覆盖默认的上传行为,可以自定义上传的实现。
代码:
<template> <el-upload :disabled="disabled" :drag="type === 'drag'" :multiple="true" action="/files/upload" :http-request="uploadRequest" :with-credentials="true" :file-list="fileList" :before-upload="beforeUpload" :on-preview="filePreview" :on-remove="fileRemove" :on-success="uploadSuccess" :on-error="uploadError"> <template v-if="type === 'button'"> <el-button class="width-7" size="small" type="primary">上传</el-button> </template> <template v-else-if="type === 'drag'"> <i class="el-icon-upload"></i> <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div> </template> </el-upload> </template> <script> import {mapActions} from 'vuex'; export default { props: { fileList: { required: true }, type: { default: 'drag' }, disabled: false, fileType: { type: String, default: 'all' }, isAttach: { default: false } }, data() { return {}; }, methods: { ...mapActions([ 'deleteFile' ]), beforeUpload(file) { if (this.fileType === 'emergency') { let str = 'pdf,bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw'; if (!(str.indexOf(file.name.split('.').reverse()[0]) > -1)) { this.$message.error('文件类型错误!'); return false; } } else if (this.isAttach && file && file.size > 500 * 1024 * 1024) { this.$message.error('上传文件不得超过500M'); return false; } }, filePreview(file) { window.open(file.url); }, fileRemove(file) { if (file && file.id && !this.isAttach) { this.deleteFile(file.id).then(() => { this.$emit('attachmentDelete', file.id); this.$message({message: '文件删除成功', type: 'success'}); }).catch(() => { this.$message.error(`文件“${file.name}”删除失败`); }); } else if (this.isAttach && file && file.attachmentId) { this.deleteFile(file.attachmentId).then(() => { this.$emit('attachmentDelete', file.attachmentId); this.$message({message: '文件删除成功', type: 'success'}); }).catch(() => { this.$message.error(`文件“${file.name}”删除失败`); }); } }, uploadSuccess(response) { if (response) { this.$message({message: '文件上传成功', type: 'success'}); this.$emit('uploadSuccess', response); } }, uploadError(err, file) { if (err) { this.$message.error(`文件“${file.name}”上传失败`); } }, uploadRequest(param) { let fileObj = param.file; let form = new FormData(); form.append('file', fileObj); this.$axios.$post(`/files/upload`, form, { process: function (event) { param.file.percent = event.loaded / event.total * 100; param.onprogress(param.file); } }).then(res => { this.uploadSuccess(res); }).catch(res => { this.uploadError(); }); } } }; </script>