tags:

views:

7717

answers:

4

Implementing a file upload under html is fairly simple, but I just noticed that there is an 'accept' attribute that can be added to the <input type="file" ...> tag.

Is this attribute useful as a way of limiting file uploads to images, etc? What is the best way to use it?

Alternatively, is there a way to limit file types, preferably in the file dialog, for an html file input tag?

+11  A: 

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. Using client-side scripting, you can make a sort of extension based validation, for submit data of correct type (extension).

Other solutions for advanced file uploading require Flash movies like SWFUpload or Java Applets like JUpload.

CMS
+1  A: 

If the browser uses this attribute, it is only as an help for the user, so he won't upload a multi-megabyte file just to see it rejected by the server...
Same for the <input type="hidden" name="MAX_FILE_SIZE" value="100000"> tag: if the browser uses it, it won't send the file but an error resulting in UPLOAD_ERR_FORM_SIZE (2) error in PHP (not sure how it is handled in other languages).
Note these are helps for the user. Of course, the server must always check the type and size of the file on its end: it is easy to tamper with these values on the client side.

PhiLho
+1  A: 

According to w3schools, no browsers properly support the attribute. Some browsers does allow image/gif, image/jpeg though. It would be best to validate the value in the input with javascript and on the server side.

If you are using ASP.NET you could drop a RegularExpressionValidator and use the expression ^.+\.ext$ where ext is the extension you want.

Li Huan
can you please give an example?
kapil
@Li Huan - you still need to verify, on the server side, that I didn't just rename my file from `virus.exe` to `benign.jpeg` -- and if you give an example to kapil it should accept at least .jpg .jpeg and .jpe if it were filtering for Jpeg image files.
Stephen P
A: 

how to ban some file format in file input tag.

bayarja
Probably best not to add anything unless it's a valid answer...
Darren Oster