核心思想是通过模拟点击事件和promise.all实现判断多图和单图上传
HTML 部分
<div class="all-box">
<div class="left-box">
<h1>门店图</h1>
<div class="btn">
<el-button size="small" type="primary" @click="handleChange(false)">选择上传文件</el-button>
</div>
<div class="img-box" v-if="leftList.length > 0">
<el-image v-for="(item, index) in leftList" :key="index" :src="api.imgBaseUrl + item.fileUrl"></el-image>
</div>
<div v-else>
<h1>暂无图片</h1>
</div>
</div>
<div class="right-box">
<h1>相册</h1>
<div class="btn">
<el-button size="small" type="primary" @click="handleChange(true)">选择上传文件</el-button>
</div>
<div class="img-box" v-if="rightList.length > 0">
<el-image v-for="(item, index) in rightList" :key="index" :src="api.imgBaseUrl + item.fileUrl"></el-image>
</div>
<div v-else>
<h1>暂无图片</h1>
</div>
</div>
</div>
<input v-show="false" ref="fileRef" multiple="multiple" type="file" @change="fileChange" accept="image/*" />
JS部分
//上传图片
handleChange(e) {
this.type = e;//判断是否走多图上传
this.$refs.fileRef.dispatchEvent(new MouseEvent('click'));//模拟点击事件
},
fileChange(e) {
try {
let files = e.target.files || e.dataTransfer.files;//获取input上传信息
this.upLoader(files);//调用上传图片方法
} catch (error) {
this.$message({
message: '上传失败',
type: 'error'
});
}
},
async upLoader(file) {
let subFunc = null;//判断走单图保存方法还是多图保存方法
let options = null;//保存方法的参数
let arr = [];
for (let i = 0; i < file.length; i++) {
const formData = new FormData();
formData.append('file', file[i]);
let data = formData;
arr.push(imgUpload(data));//往数组中上传接口完成后的pushpremi对象,imgUpload是上传的方法
}
Promise.all(arr).then(async (data) => {
let file = data.map((e) => {
return {
businessId: this.id,
fileName: e.data.fileName,
fileUrl: e.data.completeFilePath
};
});//file是上传接口返回的信息,是保存是需要携带的参数
if (!this.type) {
subFunc = photoMasterImg;
options = file[0];
} else {
subFunc = photoAlbum;
options = file;
}//通过type确定需要保存的参数
let { data: res1 } = await subFunc(options);
if (res1.code == '200') this.getPhotoAll();
});
}