vue3 使用 ElementPlus upload 上传文件的两种方式:使用 action 和不使用 action。
一、使用 action 上传
html 部分(上传多个文件):
<el-upload action="uploadUrl" list-type="picture-card" v-model:file-list="formData.fileList" :limit="9" accept="image/*" :before-upload="beforeUpload" :on-success="handleSuccess"> <el-icon> <Plus /> </el-icon> <template #file="{ file }"> <div> <img :src="file.url" alt="" /> <span > <span @click="handleRemove(file)"> <el-icon> <Delete /> </el-icon> </span> </span> </div> </template> </el-upload>
js 部分:
const uploadUrl = import.meta.env.VITE_APP_HOSTURL + "/imgUpload/upload"; const handleRemove = (file) => { for (let i = 0; i < formData.fileList.length; i++) { let item = formData.fileList[i] if (item.uid === file.uid) { formData.fileList.splice(i, 1) return true } } console.log(file) } const beforeUpload = (file) => { const isLtSize = file.size / 1024 / 1024 < 5; if (!isLtSize) { ElMessage.error("上传图片大小不能超过 5MB!"); return false; } return true; } const handleSuccess = (file) => { console.log(file) }
二、不使用 action
html 部分(上传单个文件):
<el-upload action="#" :limit="1" :show-file-list="false" :http-request="handleUpload" :before-upload="handleChange" accept=".png,.jpe,.jpeg" ref="uploadBanner" > <img v-if="formData.appLogo" :src="formData.appLogo" /> <el-icon v-else ><Plus /></el-icon> <el-icon v-if="formData.appLogo" @click.stop="clearUploadImg" ><CircleCloseFilled /></el-icon> </el-upload>
js 部分:
// 上传 const handleChange = (rawFile) => { if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") { ElMessage.error("只能上传 jpeg/jpg/png 图片"); return false; } else if (rawFile.size / 1024 / 1024 > 1) { ElMessage.error("上传图片最大不超过 1MB!"); return false; } return true; }; const handleUpload = async (file) => { let fd = new FormData(); fd.append("file", file.file); // 这里是请求上传接口 let result = await uploadFile(fd); if (result.code == 200) { // 后台只返回文件名称,需要拼接 formData.value.appLogo = import.meta.env.VITE_APP_HOSTURL + import.meta.env.VITE_APP_BASEURL + "file/previewFile/" + result.data; // 去掉 form 表单验证的* // formRef.value.clearValidate(['appLogo']) // 上传成功清空文件 uploadBanner.value.handleRemove(file); } else { formData.value.appLogo = ""; ElMessage.error(result.message); uploadBanner.value.handleRemove(file); } }; const clearUploadImg = (file) => { formData.value.appLogo = ""; uploadBanner.value.clearFiles(); };