I am using antd’s Upload component to take files input in React. My usecase allows only specific types of file to be permitted to upload. I am using beforeUpload prop of Upload component to conditionally check the type of the file before proceeding to upload. The problem is, the file type is empty string on some cases. First I thought it is OS-related issue as it was occuring on Macbook while working fine on Windows. But, it also works fine on some of the Mac devices. I am unable to identify the root cause of the issue. I also thought maybe the issue is with the file itself, but the same file retrieves correct file type on one device while empty string on the other with same browser type and version.
Here’s the code I am using:
export const ATTACHMENT_ALLOWED_FILE_TYPES = [
"application/x-zip-compressed",
"application/x-rar-compressed",
"application/x-compressed",
"application/zip", // mac format for zip
"application/x-rar", // mac format for rar
"application/vnd.rar", // MIME type for .rar files
"application/x-compressed",
"image/jpeg",
"image/png",
"image/jpg",
"application/pdf",
"application/vnd.ms-excel", // Excel 97-2003
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // Excel 2007+
"application/vnd.ms-powerpoint", // PowerPoint 97-2003
"application/vnd.openxmlformats-officedocument.presentationml.presentation", // PowerPoint 2007+
"application/msword", // Word 97-2003
"application/vnd.openxmlformats-officedocument.wordprocessingml.document", // Word 2007+
];
export const isFileTypeAllowed = (file) => {
console.clear();
console.log("File Type: ", file);
const isFileTypeSupported = ATTACHMENT_ALLOWED_FILE_TYPES.includes(file.type);
return isFileTypeSupported;
};
const uploadOptions = (questionId) => ({
name: "attachments",
showUploadList: true,
beforeUpload(file) {
const isFileTypeSupported = isFileTypeAllowed(file);
if (!isFileTypeSupported) {
notification(
NotificationTypes.ERROR,
resources_EN.ERROR_LABEL,
resources_EN.FILE_TYPE_ERROR,
3
);
return Upload.LIST_IGNORE;
} else {
const fileSizeLimit = isFileSizeValid(file);
if (!fileSizeLimit) {
notification(
NotificationTypes.ERROR,
resources_EN.ERROR_LABEL,
resources_EN.FILE_SIZE_ERROR,
3
);
return Upload.LIST_IGNORE;
}
}
customRequest({ file, questionId });
return false;
},
onRemove: (file) => {
handleFileRemove(file);
},
});
<Form.Item
name={[index, FORM_VALIDATION_KEYS.ATTACHMENT]}
valuePropName="fileList"
getValueFromEvent={normFile}
>
<Upload {...uploadOptions(question.questionId)}>
<Button className="submitBtn" title={resources_EN.ADD_ATTACHMENTS} />
</Upload>
</Form.Item>;
Works correctly on most of the devices: Correct Example – Console logs
But in few cases, doesn’t retrieve file: Example where type = “”