DEV Community

Cover image for How To Only Accept Images using HTML
Code And Deploy
Code And Deploy

Posted on • Updated on

How To Only Accept Images using HTML

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/html/how-to-only-accept-images-using-html

Advanced Laravel SAAS Starter Kit with CRUD Generator

Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!

In this post, I will share how to only accept images or specific extensions using HTML. Using this method will help to add extra checking before uploading images to your server. We will use the accept="" attribute with the specified extensions that you want to allow to upload.

Here is an example of how to do it.

<input type="file" name="file" class="form-control" accept=".jpg,.jpeg,.bmp,.png,.gif">
Enter fullscreen mode Exit fullscreen mode

As you can see I added .jpg, .jpeg, .bmp, .png, .gif as value with accept attribute. Now using this you only show images with have this extension on a dialog box.

Advanced Laravel SAAS Starter Kit with CRUD Generator

Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/html/how-to-only-accept-images-using-html if you want to download this code.

Happy coding :)

Top comments (6)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

It is a much better idea to use both the file extensions and mime/media types in the accept attribute - this will make it more likely that the files are actually images (and not just files that happen to have the correct extension)

Collapse
 
codeanddeploy profile image
Code And Deploy

Great. Thanks for the idea.

Collapse
 
andreasvirkus profile image
ajv

Yes, I agree with Jon here - something like accept="image/*" would be better. You also wouldn't have to worry about manually maintaining the list, for instance right now it's missing .webp and some other modern extensions.

Collapse
 
codeanddeploy profile image
Code And Deploy

Yeah your are right. Thank you.

Collapse
 
lexlohr profile image
Alex Lohr

In any case, you should also make sure that the server will enforce format/size requirements itself, since an attacker could attempt to programmatically initiate the upload to add wrong formats intended to be misinterpreted by your server or files that are too large in order to cause a denial-of-service (DoS).

Collapse
 
codeanddeploy profile image
Code And Deploy

Yes.. another validation in backend.