使用FileLoader对上传的文件进行检测
文件检测相关
使用FileLoader对上传的文件进行检测
可以检测文件类型、文件大小、文件长宽比 文件的大小可以用file.size进行比较,单位是byte 例子:
function validateImageFile(file) {
return new Promise((resolve, reject) => {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp'|| file.type === 'image/avif';
if (!isJpgOrPng) return reject(new Error('只能上传JPG/PNG/WEBP/AVIF格式的文件'))
const reader = new FileReader();
reader.onload = function(event) {
const img = new Image();
img.onload = function() {
const width = img.naturalWidth;
const height = img.naturalHeight;
const aspectRatio = width / height;
if (aspectRatio > 2 || aspectRatio < 0.5) return reject(new Error('图片比例不超过2:1'))
resolve(true)
};
img.onerror = function() {
reject(new Error("无法读取图像文件"));
};
img.src = event.target.result;
};
reader.onerror = function() {
reject(new Error("无法读取文件"));
};
reader.readAsDataURL(file);
}).catch(err => {
message.warning(err.message);
return false
})
}
File 接口基于 Blob,继承了 blob 的功能并将其扩展以支持用户系统上的文件。因为File对象是一种特殊类型的blob
FileReader.readAsDataURL()开始读取指定的 Blob 中的内容。一旦完成,result 属性中将包含一个表示文件数据的 data: URL。
FileLoader参考链接: https://segmentfault.com/a/1190000022113605 https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader