一、自动上传和手动上传
上传图片分两种,自动上传和手动上传,效果区别:
自动上传:选择图片后立刻调接口上传图片
手动上传:选择图片后只显示图片,自定义何时上传,可以定义点击确定事件里表单验证成功后上传图片
区别:自动上传会造成很多脏数据,手动上传等到上传时才校验图片是否合规
二、手动上传
表单中使用el-upload手动上传图片,组件选择的是照片墙
<template>
<el-form
ref="cardFormRef"
:model="cardForm"
:rules="rules"
label-width="120px"
class="demo-cardForm"
status-icon
>
<el-form-item label="轮播图" prop="photo">
<el-upload
ref="uploadRef"
:class="{ iconVis: fileList.length }"
:action="url" //上传接口
v-model:file-list="fileList"
:limit="1" //限制上传一张
list-type="picture-card" //照片墙
:before-upload="beforeUpload" //上传前
:on-success="handleAvatarSuccess" //上传成功
:headers="headers"
:auto-upload="false" //手动上传
>
<el-icon class="avatar-uploader-icon"><Plus /></el-icon>
</el-upload>
</el-form-item>
</el-form>
</template>
var fileList = ref([]);
var uploadUrl = ref(false); //存图片成功返回的url
const headers = ref({ Authorization: "Bearer " + getToken() });
var url =import.meta.env.VITE_APP_BASE_API + "接口";
var rules = computed(() => ({ //表单校验规则
photo: [
{
required: true,
message: "请上传图片",
trigger: "blur",
},
]
}));
var beforeUpload = (file) => {
console.log("上传前");
const isJPG =
file.type === "image/jpeg" ||
file.type === "image/png" ||
file.type === "image/jpg";
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
proxy.$modal.msgError("上传图片只能是 JPG/PNG 格式!");
}
if (!isLt2M) {
proxy.$modal.msgError("上传图片大小不能超过 2MB!");
}
isJPG && isLt2M ? (uploadUrl.value = true) : (uploadUrl.value = false);
return isJPG && isLt2M;
};
function handleAvatarSuccess(res, file) {
console.log("成功了!");
let { url } = res.data;
uploadUrl.value = url;
sumbitForm(); //表单提交接口,传uploadUrl
}
var cardFormRef=ref(null);
var uploadRef=ref(null);
var sumbit = () => { //点击确定按钮,进行表单校验,校验成功上传图片
cardFormRef.value.validate((val) => {
if (val) {
console.log("上传图片");
uploadRef.value.submit();
}
});
};
点击确定sumbit,表单校验成功 => beforeUpload检查图片符合规格 => handleAvatarSuccess图片上传成功 =>sumbitForm提交表单,包含图片上传成功返回的url