移动端上传图片组件:van-uploader
一、上传图片之前::before-read="BeforeRead"
BeforeRead:代码如下
BeforeRead(file) {
if (file instanceof Array && file.length) {
file.forEach((item) => {
if (
item.type !== "image/jpeg" &&
item.type !== "image/png" &&
item.type !== "image/jpg"
) {
this.$toast.fail("请选择正确图片格式上传");
return false;
}
});
return file;
} else {
if (
file.type !== "image/jpeg" &&
file.type !== "image/png" &&
file.type !== "image/jpg"
) {
this.$toast.fail("请选择正确图片格式上传");
return false;
}
return file;
}
},
二、删除图片::before-delete="BeforeDelete"
BeforeDelete代码如下:
BeforeDelete(file, name) {
this.lstFj.splice(name.index, 1);
return true;
},
其中:this.lstFj是你之后要上传的图片的集合
三、:after-read="AfterRead"
AfterRead代码如下:
AfterRead(file, obj) {
//在页面有多条需要上传图片的时候,上传图片单独用函数写
this.uploadSingleImage(file, this.lstFj, this.files);
},
//
uploadSingleImage(file, parentObj, fileList) {
if (!file) {
return;
}
// console.log("111");
const toast = this.openLoading("正在上传图片...");
let that = this;
const params = new FormData();
params.append("file", file.file, `${new Date()}.png`);
params.append("metaguid", 1);
params.append("dataName", `${new Date()}.png`);
params.append("filesourcetype", "文档入库");
axios
.post(
`接口`,
params,
{
headers: {
"Content-Type": "multipart/form-data",
},
}
)
.then((res) => {
if (!res.data.data) {
fileList.splice(fileList.length - 1, 1);
Toast.fail(res.data.message);
return;
}
const fj = {
CaseNo: this.$route.params.CASENO,
FjBakInfo: file.content,
FjFormat: file.file.type,
FjID: res.data.data,
FjName: file.file.name,
FjOrder: "",
};
parentObj && parentObj.push(fj);
toast.clear();
Toast.success("上传成功");
})
.catch((err) => {
toast.clear();
console.log(err);
Toast.fail("文件上传失败,存在同名文件");
});
},
其中this.lstFj是之后整个页面保存是上传的, this.files是组件v-model的对象
四、其中,当mounted时有需要显示的图片
this.LoadPictures(this.lstFj, this.files);
LoadPictures(lstFj, parentFiles) {
if (!lstFj || !parentFiles) {
return;
}
if (lstFj.length > 0) {
lstFj.forEach((item, index) => {
const id = item.FjID;
if (id) {
axios
.get(
`接口`,
{
responseType: "blob",
}
)
.then((res) => {
if (res?.status === 200) {
const data = res.data;
this.getBase64(data).then((result) => {
// console.log("图片", index);
const zj = { ...lstFj[index] };
parentFiles.push({
...zj,
content: result,
type: res.data.type,
size: res.data.size,
file: new File([res.data], item.FjName, {}),
isImage: true,
});
});
}
})
.catch((err) => {
console.log(err);
});
}
});
}
},
这是在最初的时候给files传已有的图片的lstFj的时候。