vue实战(14)——基于Element图片批量上传
2020-04-13 本文已影响0人
wayne1125
1、运用场景
image.png<el-form-item label="主相册:" prop="picAddressList">
<span class="advice-size">建议尺寸: 750 * 500</span>
<el-upload class="avatar-uploader-multi" accept="image/*" :file-list="picAddressList" :headers="myHeaders" :action="api/uploadImage`" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-success="(response, file) => handlePictureCardSuccess(response, file)" :on-remove="handleRemove" :before-upload="beforeUpload" multiple>
<i class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
</el-form-item>
// 主相册
handlePictureCardSuccess (response, file) {
// console.log执行了三次
if(response.code == 1) {
this.picAddressList.push({
"url": global.imgPath + response.data.url
})
this.formData.picAddressList.push(response.data.url)
}
// console.log执行了一次
},
- 原本单图上传的配置上加了multiple属性,选择3个图片文件后,一次性请求了3次接口,图片却只增加了一张,中间出现了三张闪一下又只剩一张了
- 排查代码是this.picAddressList.push的过程中只执行了最后一次push,进一步改造上传push处理应该能解决
- 翻阅了Element的上传api,找到了多图上传的相应方法,需要后端配合提供一个多图上传的接口
2、实现代码
<template>
<div>
<el-upload
:multiple="multiple"
:headers="myHeaders"
action="api/uploadImage"
list-type="picture-card"
:auto-upload="false"
:http-request="uploadFile"
ref="upload"
:on-preview="handlePictureCardPreview"
>
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
<el-button @click="subPicForm">提交上传</el-button>
</div>
</template>
<script>
import axios from 'axios'
export default {
data(){
return {
formDate:"",
dialogVisible: false,
dialogImageUrl: '',
}
},
methods:{
uploadFile(file){
this.formDate.append('file', file.file);
},
subPicForm(){
this.formDate = new FormData()
console.log(this.formDate)
this.$refs.upload.submit();
let config = {
headers: {
'Content-Type': 'multipart/form-data',
'x-access-token': 'token'
}
}
console.log(this.formDate,config)
axios.post(`api/uploadImage`, this.formDate,config).then( res => {
console.log(res)
}).catch( res => {
console.log(res)
})
}
}
}
image.png
image.png