/

How to Restrict File Uploads to Images in an Input Field

How to Restrict File Uploads to Images in an Input Field

If you are looking to create an input field that only allows users to upload images, there is a simple solution. By adding the accept attribute to your input element, you can specify the file types that are allowed to be uploaded.

To allow all image file types, use the following code:

1
<input type="file" accept="image/*">

If you only want to allow PNG images, you can use the following code:

1
<input type="file" accept="image/png">

You can also apply the same syntax to restrict uploads to videos or audio files. For example, to only accept videos, use:

1
<input type="file" accept="video/*">

And to only accept audio files, use:

1
<input type="file" accept="audio/*">

If you want to allow a combination of file types, simply separate them with commas:

1
<input type="file" accept="image/*,audio/*,video/*">

Additionally, if you want to allow users to upload multiple images at once, you can add the multiple attribute to the input element:

1
<input type="file" multiple accept="image/*">

Please note that the accept attribute only provides client-side validation. To ensure the uploaded files are indeed images on the server-side, you will need to validate the MIME type of the received files as well.