vue:
<div
class="img-box"
v-for="(item, idx) in picList"
:key="item.url + idx"
>
<img class="img" :src="item.url" />
<i
class="el-icon-circle-close img-close"
@click="handleRemove(idx)"
></i>
</div>
<el-upload
v-if="picList.length < 9"
:action="action"
:headers="headers"
ref="imgUpload"
accept="image/png, image/jpeg, image/gif"
:on-success="handleUploadSuccess"
:before-upload="beforeAvatarUpload"
multiple
:show-file-list="false"
:on-exceed="handleExceed"
:limit="9 - picList.length"
>
<i class="el-icon-plus"></i>
</el-upload>
<div class="upload-tip">支持9张内,不超过10M的jpg、png、gif文件</div>
js:
beforeAvatarUpload(file) {
// const isJPG = file.type === "image/jpeg";
// const isPng = file.type === "image/png";
const isLt10M = file.size / 1024 / 1024 < 10;
// if (!isJPG && !isPng) {
// this.$message.error("上传图片只能是 JPG或png 格式!");
// }
if (!isLt10M) {
this.$message.error("上传图片大小不能超过 10MB!");
}
// return (isJPG || isPng) && isLt10M;
return isLt10M
},
// 文件超出限制
handleExceed() {
this.$message.error("你最多能发布9张照片");
// 清空已上传的文件列表,不然数量限制会有问题
this.$refs.imgUpload.clearFiles();
},
// 上传成功回调
handleUploadSuccess(res, file) {
if (res.code === 200) {
this.picList.push({
url: res.url,
uploadUrl: res.fileName,
});
} else if (res.code === 401) {
this.$alert("登录状态已过期,请重新登录", "系统提示", {
confirmButtonText: "重新登录",
callback: () => {
this.$store.dispatch("LogOut").then(() => {
// token失效后续操作
});
},
});
} else {
this.$message.error(res.msg || "上传失败");
this.$refs.imgUpload.clearFiles();
}
},
handleRemove(idx) {
this.picList.splice(idx, 1);
},
说明:
1、已上传的图片列表展示自己写,不然一旦后端接口报错提示上传失败,页面却成功展示出来图片,有点误导
2、图片数量超出限制或者上传失败的情况加上这段代码,不然第二次去选择照片可能会报超出限制的错误,实际可能没有超出数量限制~