How to make sure your input field can only upload images

By

Learn how to restrict a file input to images only using the HTML accept attribute with values like image/* or image/png, and why you validate server-side too.

~~~

To restrict a file input to images, add the accept attribute with the value image/*. The browser’s file picker will then only show image files.

Here’s how I got there. I had the need to have a file upload for images, so I added my little input type="file" field:

<input type="file">

I only wanted images to be allowed to be uploaded by the browser.

It’s a common thing, but I always forget how to do it.

The accept attribute

Use the accept attribute and pass image/* to allow all images:

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

Or image/png to only accept PNG images:

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

You can also pass file extensions, each starting with a dot:

<input type="file" accept=".png,.jpg,.jpeg">

The same syntax works to only accept videos:

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

or audio:

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

Or a combination of them:

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

Oh, common thing: add multiple to allow uploading more than one file:

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

What does accept actually do?

It filters the file picker dialog. When the user clicks the input, the dialog pre-selects a filter matching your accept value, so they only see images.

That’s a convenience for the user, not a security measure. On most platforms the picker has an “All files” option, and the user can switch to it and select a PDF anyway. Drag and drop onto the input can also bypass the filter in some browsers.

Checking the file in JavaScript

If you want a second check before uploading, read the file’s MIME type:

const input = document.querySelector('input[type="file"]')

input.addEventListener('change', () => {
  const file = input.files[0]
  if (file && !file.type.startsWith('image/')) {
    alert('Please select an image')
    input.value = ''
  }
})

file.type gives you the MIME type the browser detected, like image/jpeg.

Of course this is all client-side validation, and you should also validate the MIME type on the server when you receive the files. Anyone can send a request to your upload endpoint without going through your form at all.

Tagged: HTML · All topics
~~~

Related posts about html: