tags:

views:

898

answers:

5

If I have an HTML file input field, is there any way that I can limit it to only allow image uploads? I'm sure this would be possible with Flash or Java, but I'm trying to stay away from them for the time being.

I found the "accept" attribute online, but it doesn't seem to be doing anything for me (or I'm using it wrong.). Any help or examples is appreciated.

A: 

There is no way to limit the types x-browser.

redsquare
+3  A: 

The best way is to handle that in the backend. Depending on the type of types you want to allow and the backend technology you will find various ways of doing this.

You can also do this in javascript but you'll be more limited and it might lead to issues crossbrowser:

if((document.form1.upload.value.lastIndexOf(".jpg")==-1) {
   alert("Please upload only .jpg extention file");
   return false;
}

(via)

If you use jquery, checkout this question: http://stackoverflow.com/questions/651700/how-to-have-jquery-restrict-file-types-on-upload

You can also use the JQuery Validation plugin.

$("#myform").validate({
  rules: {
    field: {
      required: true,
      accept: "xls|csv"
    }
  }
});

(via)

marcgg
+1. Doing it in the backend is a must; the client-side check should only be there to save the user from uploading things that will be rejected.
You
Does this go by "field" as being the element id, class, or name?
Mike Trpcic
I'm not sure, I'd say ID but you'll have to double check with the documentation they have online
marcgg
A: 

Hi,

According to this answer (quoting) :

Accept attribute was introduced in the RFC 1867, intending to enable file-type filtering based on MIME type for the file-select control. But most, if not all, browsers make no use of the this attribute.

I'm guessing you'll still have to deal with "wrong" files in you script on the server... even if you find some Javascript way of checking that (there might be -- see other answers), you will always have to check data on the server, as JS can be disabled, and forms posting faked...

Pascal MARTIN
A: 

Using javascript you can do it, by checking what was changed in the filename text box, or on the submit button that may be used.

This site has an example of doing this: http://www.codestore.net/store.nsf/unid/DOMM-4Q8H9E

If you are really cautious though you should also verify on the backend, as I could put a .jpg on the end of any file and it would pass the javascript check.

James Black
A: 

Well, you can do that using Javascript, actually if you are using jQuery, almost all file-upload plugins can optionally handle file type limiting. Only HTML won't do it.

But only client-side filtering doesn't mean any type of file can't be uploaded to your server. Actually attacker can upload any kind of file, because it's simple to avoid Javascript 'shield'. You must always do the server-side validation.

usoban