How to get the HTML's input element of "file" type to only accept pdf files?

To get the HTML file input form element to only accept PDFs, you can use the accept attribute in modern browsers such as Firefox 9+, Chrome 16+, Opera 11+ and IE10+ like such:

You can string together multiple mime types with a comma.

The following string will accept JPG, PNG, GIF, PDF, and EPS files:

In older browsers the native OS file dialog cannot be restricted – you'd have to use Flash or a Java applet or something like that to handle the file transfer.

And of course it goes without saying that this doesn't do anything to verify the validity of the file type. You'll do that on the server-side once the file has uploaded.

A little update – with javascript and the FileReader API you could do more validation client-side before uploading huge files to your server and checking them again.

answered Jun 27, 2012 at 16:47 Charlie Schliesser Charlie Schliesser 8,179 4 4 gold badges 47 47 silver badges 78 78 bronze badges

The accept attribute value is a string that defines the file types the file input should accept. You can use the accept attribute like:

or you can specify a unique file type specifier:

answered Sep 27, 2021 at 16:16 Kaiwen Luo Kaiwen Luo 485 7 7 silver badges 10 10 bronze badges 1 1 1 silver badge answered Oct 10, 2009 at 15:15 Jonathan Feinberg Jonathan Feinberg 45.1k 7 7 gold badges 82 82 silver badges 103 103 bronze badges

+0. I would agree if you instead had said "yes, but not really". Especially now that Chrome supports it, and I think Opera might too.

Commented Nov 4, 2011 at 14:04

The previous posters made a little mistake. The accept attribute is only a display filter. It will not validate your entry before submitting.

This attribute forces the file dialog to display the required mime type only. But the user can override that filter. He can choose . and see all the files in the current directory. By doing so, he can select any file with any extension, and submit the form.

So, to answer to the original poster, NO. You cannot restrict the input file to one particular extension by using HTML.

But you can use javascript to test the filename that has been chosen, just before submitting. Just insert an onclick attribute on your submit button and call the code that will test the input file value. If the extension is forbidden, you'll have to return false to invalidate the form. You may even use a jQuery custom validator and so on, to validate the form.

Finally, you'll have to test the extension on the server side too. Same problem about the maximum allowed file size.