Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

restrict file upload selection to specific types

Anyway to restrict the selection of file types via the <input type="file" /> element?

For instance, if I wanted only images types to be uploaded, I would restrict the possible selections to (image/jpg,image/gif,image/png), and the selection dialog would grey out files of other mime types.

p.s. I know that I can do this after the fact with the File API by scanning the .type attributes. I'm really trying to restrict this before hand.. I also know I can do this via flash, but I do NOT want to have use flash for this.

like image 326
ndmweb Avatar asked Sep 27 '11 20:09

ndmweb


People also ask

How do I restrict a file type in Fileupload control in asp net?

User could simply rename the extension of an unwanted file to something in the accept list. So you should approach the accept list in the file upload as a simple help to the user and at least validate on the back end.


2 Answers

There is an html attribute for this specific purpose called accept but it has little support across browsers. Because of this server side validation is recommended instead.

<input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" /> 

If you don't have access to the backend have a look at a flash based solution like SWFUpload.

See more on this here: File input 'accept' attribute - is it useful?

like image 58
amosrivera Avatar answered Sep 22 '22 15:09

amosrivera


It's better to let user select any file, and then check its type - this is better supported by the browsers:

var     file = (el[0].files ? el[0].files[0] : el[0].value || undefined),     supportedFormats = ['image/jpg','image/gif','image/png'];  if (file && file.type) {     if (0 > supportedFormats.indexOf(file.type)) {         alert('unsupported format');     }     else {         upload();     } } 

You can also check for file size using file.size property.

like image 25
Radek Pech Avatar answered Sep 22 '22 15:09

Radek Pech