前提
antd-upload组件需要支持png、jpeg、jpg、heic四种格式的图片
问题描述
windows 中上传 heic 图片无法识别出文件类型是image/heic,导致该类型被拦截,上传失败,如下图:
原因分析:
type为空,导致无法识别出heic格式的文件
解决方案:
heic2any插件转换为 jpg 格式的 file 在 beforeUplode 中 return 出去
npm i heic2any;
import heic2any from 'heic2any';
const isHeicOrHeif = (fileName:string) => {
return /\.(heic|heif)$/i.test(fileName);
};
const beforeUpload = async (file: any) => {
if(picLength >= 5) {
return Upload.LIST_IGNORE;
}
if(isHeicOrHeif(file?.name?.toLowerCase())) {
let blob: any = undefined
try {
blob = await heic2any({ blob: file, toType: "image/jpeg" });
} catch(error) {
message.warning("请上传JPG/JPEG/PNG/HEIC/HEIF格式的图片");
return Upload.LIST_IGNORE;
}
const convertedFile = new File([blob], file?.name?.replace(/\.(heic|heif)$/i, ".jpg"), {
type: "image/jpeg",
});
return convertedFile;
} else if(!["image/png", "image/jpeg", "image/jpg"].includes(file.type)) {
message.warning("请上传JPG/JPEG/PNG/HEIC/HEIF格式的图片");
return Upload.LIST_IGNORE;
}
if(file.size >= 5 * 1024 * 1024) {
message.warning('单张图片最大5M');
return Upload.LIST_IGNORE;
}
return true;
}