Search code examples
javascriptfilereader

JavaScript FileReader API isn't respecting accept type


I am using the JavaScript FileReader to upload files in my web application. I want to restrict the accepted file types to only .pem and .key. However, I noticed that I am able to upload .crt and .cer files as well. Is there something wrong with my implementation? I am using the following code:

<input
  type="file"
  accept=".key, .pem"
/>

Solution

  • The accept attribute doesn't work in the way it seems you expect it to. Here's a relevant excerpt from MDN's documentation:

    The accept attribute doesn't validate the types of the selected files; it provides hints for browsers to guide users towards selecting the correct file types. It is still possible (in most cases) for users to toggle an option in the file chooser that makes it possible to override this and select any file they wish, and then choose incorrect file types.

    Because of this, you should make sure that expected requirement is validated server-side.