Back to topics

Pitfalls When Checking File Types During Upload

When developing a file upload function, the frontend usually obtains the file via <input type="file" />, then retrieves the file's MIME type through file.type to validate the file type.

But the pitfall I encountered today was that the tester couldn't upload the file no matter how they tried, with an error indicating an incorrect file type.

Solution Approach

To pinpoint the issue, I printed the file instance before uploading. I found that on the tester's computer, the type of the uploaded file was an empty string.

Once I knew where the problem was, it became easy to solve.

Code Implementation

// Get extension from file name
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('Attachment format not supported');
     uploadStatus.value = UPLOAD_STATUS.READY;
     // others
 }