3

iview实现文件上传 限制上传格式、大小

 1 year ago
source link: https://blog.51cto.com/u_15723831/5810322
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

iview实现文件上传 限制上传格式、大小

精选 原创

问题描述:下面以CRMEB Pro版产品为例

1.当上传的文件格式类型不为jpeg、png、gif、jpg时,提示上传的文件格式不正确

2.当上传的文件大小超过后端返回的大小时,提示文件体积过大

需要限制文件上传的格式和大小,最后的实现效果如下:

iview实现文件上传 限制上传格式、大小_文件大小
iview实现文件上传 限制上传格式、大小_前端页面_02

对于文件大小的限制是可配置的,接口返回一个字段,我存了缓存,在上传图片的组件里,获取到存入缓存的这个值,在上传前对文件大小进行判断,上传的文件类型是写死了四种图片类型,在上传前通过判断文件类型确定是否能上传,不能的话就抛出一个警告。 beforeUpload函数的返回值如下:

{
uid: 1651890175890
lastModified: 1651832588481
lastModifiedDate: Fri May 06 2022 18:23:08 GMT+0800 (中国标准时间)
name: "微信图片_20220506182305.jpg"
size: 846192
type: "image/jpeg"
webkitRelativePath: ''
}

示例代码如下:

// 上传之前
beforeUpload(res) {
//控制文件上传格式
let imgTypeArr = ["image/png", "image/jpg", "image/jpeg","image/gif"];
let imgType = imgTypeArr.indexOf(res.type) !== -1
if (!imgType) {
this.$Message.warning({
content: '文件 ' + res.name + ' 格式不正确, 请选择格式正确的图片',
duration: 5
});
return false
}
// 控制文件上传大小
console.log(res.size,'文件大小');
let imgSize = localStorage.getItem('file_size_max');
//获取缓存的文件大小限制字段
let Maxsize = res.size < imgSize;
let fileMax = imgSize/ 1024 / 1024;
if (!Maxsize) {
this.$Message.warning({
content: '文件体积过大,图片大小不能超过' + fileMax + 'M',
duration: 5
});
return false
}
this.uploadData = {
pid: this.treeId,
};
let promise = new Promise((resolve) => {
this.$nextTick(function () {
resolve(true);
});
});
return promise;
},

以上就是CRMEB讲解的iview实现文件上传 限制上传格式、大小的所有内容,有不懂的可以在下方留言讨论


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK