Search code examples
javascriptreactjstypescriptfile-uploadms-word

Microsoft Word File, file type is not showing as .docx after the upload


I am writing a file uploader using react and it accepts both .docx and .pdf files.

<Input type="file" onChange={handleImageUpload} accept={'.docx, .pdf'}/>

When i upload a .docx file, the file type shows as application/vnd.openxmlformats-officedocument.wordprocessingml.document. Because of this, i can't create file type validations for uploading for .docx files as it rejects all the .docx type files. Do i need to change something specifically to overcome this situation?


Solution

  • Instead of setting the accept in the input tag, I'd go with a hook to check the file type.

    something like:

    <input type="file" onChange={handleFileUpload} accept=".docx, application/pdf" />
    

    and then

    function handleFileUpload(event) {
      const uploadedFile = event.target.files[0];
    
      // Check if the uploaded file is of the allowed MIME types
      const allowedMimeTypes = ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/pdf'];
    
      if (uploadedFile && allowedMimeTypes.includes(uploadedFile.type)) {
        // Handle the file upload
      } else {
        // Display an error message or handle invalid file types
      }
    }
    

    EDIT :

    since you're asking WHY the type is "different", here you go: MIME TYPES