vue3+ant design vue实现上传组件图片默认展示
1、需求:用户点击按钮进入弹窗,此时,上传组件需展示用户上次录入的图片。
2、代码:
<a-form-item name="fileList" label="新增图片" labelAlign="right">
<a-upload
v-model:file-list="fileList"
name="文件上传"
action=""
:customRequest="upDown"
:beforeUpload="beforeUpload"
@remove="removeFile"
list-type="picture-card"
accept=".png, .jpg, .jpeg"
>
<div>
<PlusOutlined />
</div>
</a-upload>
</a-form-item>
import { PlusOutlined } from '@ant-design/icons-vue';
const fileList = ref([]); //文件上传列表
// 表单数据对象
const formState = ref({
fileList: [],
});
const getModal = () => {
open.value = true;
getAd().then((res) => {
let obj = {
url: res.url,
};
fileList.value = [obj];
formState.value.fileList = fileList.value;
});
};
import { message } from 'ant-design-vue';
// 检查文件类型,如果文件类型正确,则继续上传,false指停止上传,true指继续上传,file是文件
const beforeUpload = (file) => {
const isImage =
file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png';
if (!isImage) {
message.error('只能上传jpg/png格式的图片!');
return false; // 阻止上传
}
return true; // 允许上传
};
const downloadUrl = ref(''); //下载地址
let list = [];
// 导入文件
const upDown = async (file) => {
// console.log('文件', file);
list = [];
const random = Math.random();
const fileName = `${random}${file.file.name}`;
getOSSSign().then(async (res) => {
const { host, dir, OSSAccessKeyId, success_action_status, Signature, policy } = res;
const formData = new FormData();
const address = dir + file.file.name; //文件名
const url = host; //解构拿到url地址便于后面调uploadOss接口
formData.append('key', address);
formData.append('OSSAccessKeyId', OSSAccessKeyId);
formData.append('Signature', Signature);
formData.append('policy', policy);
formData.append('success_action_status', success_action_status);
formData.append('file', file.file);
// 上传OSS
try {
await uploadOss({ url, formData });
} catch (e) {
message.error('上传失败');
return;
}
downloadUrl.value = host + '/' + address; //文件下载地址
list.push({ name: file.file.name, url: downloadUrl.value });
fileList.value = list; //文件列表
formState.value.fileList = fileList.value; //转存到表单数据中,便于校验
// 清除校验信息
form.value.validateFields(['fileList']);
});
};
// 删除文件
const removeFile = (file) => {
// 找到要删除的文件在 fileList 中的索引
const index = fileList.value.findIndex((item) => item.name === file.name);
if (index !== -1) {
// 创建新的文件列表并删除指定索引的文件
const newFileList = [...fileList.value];
newFileList.splice(index, 1);
fileList.value = newFileList;
// 更新 formState 中的 fileList
formState.value.fileList = newFileList;
// 清除校验信息
form.value.validateFields(['fileList']);
}
const index2 = list.findIndex((item) => item.name === file.name);
if (index2 !== -1) {
// 创建新的文件列表并删除指定索引的文件
const newList = [...list];
newList.splice(index2, 1);
list = newList;
}
};