views:

47

answers:

3
<input type='file' name='userFile'>

now when i will click the browse button, the browse dialog will show all files... what if i want to filter file types lets say

  • only images or .png & .jpg & .gifs
  • only office file like .doc & .docx & .pps

how to do it...

+1  A: 

You should use one of the plugins that use embeded Flash, since you can't do it with plain javascript

fantactuka
thanks but no thanks... i rather check for file type after it has been selected... its gonna save me a lotta work
Junaid Saeed
+1 because this is the only viable solution (although it would be nicer to post some actual links instead of a Google search that can change). @Moon you will need to check for the file type afterwards (i.e. after uploading) anyway... The only thing you can do locally after selecting is check the file extension, which is not a 100% reliable indicator of the actual file type.
Pekka
+1  A: 

There is an "accept" attribute on file input controls, where you can specify the types of files you want. From what i'm seeing, though, many browsers like to ignore it -- the file types that can be specified are MIME types, so a strictly correct browser would have to look at every file regardless of extension and see if it's an image (and if so, what type it is).

Your best bet is to check the filename after the file's selected and show an error message if a file with the wrong extension is uploaded.

cHao
"The accept attribute is not properly supported by any of the major browsers." (quoted from http://www.w3schools.com/TAGS/att_input_accept.asp)
Nick
Nick is right.. i tried that
Junaid Saeed
+1  A: 

You can't control which files can be selected, but you can read the filename with javascript after the file is chosen. You could then display a warning and/or disable the submit button if the file is the wrong type. However, remember that you can't rely on the extension to tell you whether or not the file is really of the right type. It should only be treated as a way to help users who might otherwise waste time uploading a huge file before discovering that you don't support that file type.

Here's some example code to do that. It uses jQuery, but you could do the same in plain javascript too.

$(function() {
    $('#inputId').change( function() {
        var filename = $(this).val();
        if ( ! /\.txt$/.test(filename)) {
            alert('Please select a text file');
        }
    });
});
stevemegson