Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

is there any way that html element file

<input name="file1" type="file" style="width:300px"> 

only accept PDF files and when we browse its only show PDF files...

Thanks

like image 959
air Avatar asked Oct 10 '09 15:10

air


People also ask

How do you specify a file type in input?

The <input type="file"> defines a file-select field and a "Browse" button for file uploads. To define a file-select field that allows multiple files to be selected, add the multiple attribute. Tip: Always add the <label> tag for best accessibility practices!


2 Answers

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:

<input name="file1" type="file" accept="application/pdf"> 

You can string together multiple mime types with a comma.

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

<input name="foo" type="file" accept="image/jpeg,image/gif,image/png,application/pdf,image/x-eps"> 

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.

like image 76
Charlie Schliesser Avatar answered Oct 05 '22 23:10

Charlie Schliesser


Not really. See File input 'accept' attribute - is it useful? .

like image 44
Jonathan Feinberg Avatar answered Oct 05 '22 23:10

Jonathan Feinberg