文件上传检查文件类型的坑
开发文件上传功能的时候,前端通常基于 <input type="file" /> 拿到 file,再通过 file.type 获取文件的 MIME type,借此来校验文件类型。
但今天遇到的坑是,测试无论怎么上传都传不上去,提示文件类型错误。
解决思路
我为了定位问题,在上传前打印了一下 file 实例。发现测试电脑上传的文件 type 是空字符串。
既然知道问题在哪了,就好办了。
代码实现
// 通过文件名获取扩展名
export default function getFileExtension(fileName) {
return fileName ? fileName.split('.').pop() : undefined;
}
const fileType = file.type;
const fileExt = getFileExtension(file.name);
const isAllowedMimeType = MIME_TYPES.includes(fileType);
const isAllowedExt = FILE_EXT.includes(fileExt);
const isNotAllowd = !isAllowedExt && !isAllowedMimeType;
if (isNotAllowd) {
ElMessage.error('附件格式不支持');
uploadStatus.value = UPLOAD_STATUS.READY;
// others
}