How to Define Allowed File Types for HTML File Input

What happened

Many of you may often need to restrict file types when dealing with file uploads using input type=’file’. For example, when I was working on testing image conversion functionality, I wanted to limit the uploaded files to image types only.

So, how do you handle this? This is where the accept attribute comes into play.

accept attribute

The main purpose of the ‘accept’ attribute is to restrict the types of files that can be selected. It supports various common attributes:

You can use common MIME types such as image/*, video/*, text/*, and so on.

  • image/* ➡ Supports all image types, including png, jpeg, gif, and more.

Additionally, you can restrict based on specific file extensions, such as .png, .doc, and so on.

⭐ If you need to specify multiple file types, separate them with a comma (as shown in the example below).”

Here’s a example

See the Pen input_file_accept by story zyra (@story-zyra) on CodePen.

⬆️ Here is an example I’ve written. You can try it yourself by clicking on it. You’ll notice that in the lower right corner, it changes to ‘Custom Files,’ indicating the specified file types.

Notes

While there may be different outcomes in various browsers, most browsers simply provide a default type restriction. In reality, users can still switch to select other types.

For example, in the previous demo, aside from ‘Custom Files,’ users can switch back to ‘All Files’ and select other types.

How to address this

When encountering this issue, you can’t rely solely on HTML attributes. You must use JavaScript or perform validation on the backend. Here’s a simple example of JavaScript validation.

See the Pen input_file_accept_check by story zyra (@story-zyra) on CodePen.

In this example, the validation function checkfiletype is triggered when the value of the input changes, i.e., when a file is selected for upload.

Here, we use split to split the value based on the period (‘.’). Then, we use pop to retrieve the last element from the resulting array, which is the file type we want.

If it doesn’t match, a notification is displayed, and the content is cleared.


Conclusion

The ‘accept‘ attribute is more like a feature to assist in displaying defaults rather than a true validation mechanism.

This attribute allows users to quickly filter out many unwanted files. For example, if the functionality is to upload documents, you can set it as ‘.doc, .docx, .pdf,’ and so on.

However, as mentioned in the article, a validation mechanism is still necessary. Whether it’s using JavaScript validation like the example provided or backend validation, it remains essential.

Reference

🧡 Hopefully, this post has helped you to some extent.

🧡You can support me by clicking some ad, Thanks a lot

If you got any problem about the explanation, please feel free to let me know

Some Random notes

Leave a Reply

Your email address will not be published. Required fields are marked *