项目场景:
在后台管理系统上传图片时,使用自定义的上传方法
问题描述
用element-ui + vue2.0上传多张图片,并使用自定义方法时,无法获取上传进度和上传完成后的图片列表,想要获取上传完成之后的列表
<el-upload :action="actionUrl"
multiple
ref="uploadPic"
accept="image/jpeg, image/png, image/jpg"
list-type="picture-card"
:http-request="(e) => {uploadFile(e, row)}"
:on-success="(response, file, fileList) => {uploadSuccess(fileList, row)}"
:on-remove="(file, fileList) => {removeFileList(fileList, row)}"
:file-list="row.imageCos || []"
>
<i class="el-icon-plus"></i>
</el-upload>
uploadFile({file, onProgress, onSuccess, beforeUpload}, row) {
uploadPic(file, progress => {
onProgress(progress)
}).then(res => {
onSuccess({
name: res.name,
url: res.url,
})
})
},
uploadSuccess(fileList, row) {
this.$set(row, 'imageCos', fileList)
},
removeFileList(fileList, row) {
this.$set(row, 'imageCos', fileList)
},
原因分析:
看el-upload的源码得知,在自定义的http-request的函数中,有以下几个传参
post(rawFile) {
const { uid } = rawFile;
const options = {
headers: this.headers,
withCredentials: this.withCredentials,
file: rawFile,
data: this.data,
filename: this.name,
action: this.action,
onProgress: e => {
this.onProgress(e, rawFile);
},
onSuccess: res => {
this.onSuccess(res, rawFile);
delete this.reqs[uid];
},
onError: err => {
this.onError(err, rawFile);
delete this.reqs[uid];
}
};
const req = this.httpRequest(options);
this.reqs[uid] = req;
if (req && req.then) {
req.then(options.onSuccess, options.onError);
}
},
headers、file、filename、data、action、onProgress、onSuccess、onError这几个参数可以获取,调用onProgress和onSuccess就可以实现上传进度和上传成功监听
解决方案:
上传时调用onPressgress回调,上传成功后调用onSuccess回调,在调用el-upload on-success属性,获取上传成功的列表。
<el-upload :action="actionUrl"
multiple
ref="uploadPic"
accept="image/jpeg, image/png, image/jpg"
list-type="picture-card"
:http-request="(e) => {uploadFile(e, row)}"
:on-success="(response, file, fileList) => {uploadSuccess(fileList, row)}"
:on-remove="(file, fileList) => {removeFileList(fileList, row)}"
:file-list="row.imageCos || []"
>
<i class="el-icon-plus"></i>
</el-upload>
uploadFile({file, onProgress, onSuccess, beforeUpload}, row) {
uploadPic(file, progress => {
onProgress(progress)
}).then(res => {
onSuccess({
name: res.name,
url: res.url,
})
})
},
uploadSuccess(fileList, row) {
this.$set(row, 'imageCos', fileList)
},
removeFileList(fileList, row) {
this.$set(row, 'imageCos', fileList)
},