页面组件中的代码
html代码(使用vant 组件库文件上传)
<van-field label="照片" required :rules="[{ validator: validatorImg }]">
<template #input>
<van-uploader
v-model="question.fileList"
capture="camera"
:max-count="imgMaxNum"
:before-read="beforeRead"
@click-upload="imgStr = 'fileList'"
@delete="onDelete"
multiple
/>
</template>
</van-field>
js代码
import { useUpdateFile} from '@/hooks/useUpdateImg';
const { compressPicture, onDelete } = useUpdateFile();
const validatorImg = (val) => (val.length ? true : "请上传图片");
const imgMaxNum = ref(4)
const imgStr = ref()
const question = reactive({})
const beforeRead= (file) => {
try {
question[imgStr.value] = question[imgStr.value] || [];
const res =await compressPicture(file, imgMaxNum, question[imgStr.value].length).then(res=>{
question[imgStr.value] = question[imgStr.value].concat(res);
})
} catch (err) {
console.log(err)
}
};
src/hooks/useUpdateImg.js (文件创建路径)
pnpm i image-conversion
// 安装图片压缩所需要的依赖包
import * as imageConversion from "image-conversion"
import { uploadImg, delFile } from "@/api";
import { showLoadingToast, closeToast, showToast, showNotify } from "vant";
export function useUpdateFile() {
const prefix = '获取图片资源的前缀,自行替换'
const compressPicture = (file, maxNum = 2, nowNum) => {
const compressApis = []
const num = maxNum - nowNum (计算出剩余的图片上传数量)
file = Object.prototype.toString.call(file) == '[object Array]' ? file.slice(0, num) : [file]
return new Promise((resolve) => {
showLoadingToast({
message: "正在压缩...",
forbidClick: true,
duration: 0,
});
file.forEach((file) => {
compressApis.push(
new Promise((resolve) => {
imageConversion.compressAccurately(file, 1024).then(res => {
let afterFile
if (file.size > 1024 * 1024 * 1) {
afterFile = new File([res], "0.jpg")
} else {
afterFile = file
}
resolve(afterFile)
})
})
)
})
Promise.all(compressApis).then((res) => {
closeToast();
let data = new FormData();
res.forEach((item) => { data.append("file", item) })
uploadImg(data).then((res) => {
if (res.status === 200) {
showToast("上传成功");
const result = res.data.split(',')
const imgList = result.map(v => {
return {
url: `${prefix}${v}`,
name: v
}
})
resolve(imgList)
} else {
showNotify({ type: 'warning', message: '图片上传失败' })
}
});
})
})
};
const onDelete = (file) => {
delFile(file.name).then((res) => {
res.status === 200 && showToast("删除成功");
});
};
const imgDispose = (str) => {
if (!str) return []
const fileList = [];
str.split(",").forEach((val) => {
fileList.push({
name: val,
url: `${prefix}${val}`,
});
});
return fileList
};
return { prefix, compressPicture, onDelete, imgDispose };
}