1、此处省略安装Ant Design步骤,完成安装后直接引入组件
<a-upload
:action="actionUrl" //上传文件的地址
listType="picture-card" //上传文件的类型 组件内的基本样式
:file-list="fileList" //文件列表
:data="imgData" //给上传文件传递的参数
:before-upload="beforeUpload" //预上传
@change="handleChange" //上传时做限制
@preview="handlePreview" //查看
>
<div>
<a-button class="ant-upload-text">上传文件</a-button>
</div>
</a-upload>
2、设置变量
data(){
return {
fileList:[],//列表
imgData: { //上传文件所需要的变量 (根据后端给的接口,按需求修改)
annexUrl: "",
annexType: "",
annexStyle: "",
annexSize: "",
annexName: "",
},
}
}
3、做限制
methods:{
beforeUpload(file) { //获取到需要传递的参数
console.log("file", file);
this.imgData = {
annexUrl: "/assets/images",
annexType: file.type.split("/")[0],
annexStyle: file.type.split("/")[1],
annexSize: file.size,
annexName: file.name,
};
},
handleChange(info) { 上传完成之前做限制
console.log(info);
this.annex = info.file;
let fileList = [...info.fileList];
if (info.file.status !== "removed") {
const isLt10M = info.file.size / 1024 / 1024 < 10;
if (!isLt10M) { //限制文件大小
this.$message.warning("文件大小不能超过10M!");
return;
}
const isJpgOrPng =
info.file.type === "image/jpeg" ||
info.file.type === "image/png" ||
info.file.type === "image/jpg" ||
info.file.type === "image";
if (!isJpgOrPng) { //限制文件类型
this.$message.warning("只能上传jpg/jpeg/png的文件!")
return;
}
if (info.file.name.length > 50) { //限制文件名称的长度
this.$message.warning("文件名称不能超过50个字符!");
return;
}
}
this.fileList = fileList;
},
}