前端界面:
<el-form-item label="商品轮播图" :rules="[{ required: true, message: '必须要上传图片', trigger: 'blur' }]"
prop="images">
<el-upload
ref="upload"
:action=webSite
class="upload-demo"
drag
:limit="5"
:file-list="form.file_list"
:before-upload="beforeUpload"
:on-success="handleSuccess"
:on-remove="handleRemove"
:on-exceed="handleExceed"
:headers="uploadHeaders"
:show-file-list="true"
multiple
style="float: left">
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">只能上传jpg/png文件,且不超过5M</div>
</el-upload>
</el-form-item>
其中,主要是on-success 和 on-remove需要特殊处理, form.file_list 初始化为 空列表[]
handleSuccess(response, file, fileList) {
this.$message.success('上传成功!')
this.form.image = response.url;
if (fileList.every(item => item.status === 'success')) {
fileList.map(item => {
/** 这时只需要push进带有response的数据就好 */
if (item.response) {
this.form.file_list.push({
name: item.response.file_name,
url: item.response.url
})
}
})
}
console.log(this.form.file_list)
},
handleRemove(file) {
// 通过url找到index并去除列表
const indexs = this.form.file_list.map((item, index) => index).filter(index => this.form.file_list[index].url === file.url);
for (let index of indexs) {
this.form.file_list.splice(index, 1);
}
},
后端接收 form内容,request.data,其中file_list的内容为:
'file_list': [{'name': '桃花.png', 'url': 'save_dir/13786f5bfc734da1bb1d31eecd4c453d.png', 'uid': 1692951058963, 'status': 'success'}, {'name': '1-小鸡1.png', 'url': 'save_dir/8d868dddaa7e4ffdad5ae0f077c770a9.png', 'uid': 1692951058964, 'status': 'success'}]