开发者

HTML <input type='file'> apply a filter

开发者 https://www.devze.com 2023-01-12 11:20 出处:网络
<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
<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

how to do it...


I think u are looking for the accept parameter. Try this works

<input type="file" accept="image/*" />


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).

Update: It seems at least some version of every major browser on Windows now provides at least some support for the accept attribute. (Even IE supports it, as of version 10.) However, it's still a bit early yet to rely on it, as IE 8 and 9 still don't support it. And support in general is a bit spotty.

  • Chrome seems to have full support. It uses its own built-in list of types as well as the system's...so if either one defines the type, Chrome knows which files to show.
  • IE 10 supports file extensions beautifully, and MIME types decently. It seems to use only the system's mapping of MIME type to extensions, though...which basically means if something on the user's computer didn't register those extensions with the right MIME types, IE won't show files of those MIME types.
  • Opera only seems to support MIME types -- to the point where extensions actually disable the filter -- and the UI for the file selector sucks. You have to select a type in order to see the files of that type.
  • Firefox appears to support only a limited set of types, and ignore other types as well as extensions.
  • I don't have Safari, and don't plan on downloading it. If someone could document Safari's support... Partial support on safari. http://caniuse.com/#search=accept

You should consider adding the attribute, so browsers that support it can help the user find the right files more easily. But i would still suggest that you check the filename after the file's selected and show an error message if a file with the wrong extension is uploaded.

And of course, definitely have the server double-check that the file is the right type. File extensions are just a naming convention, and can be easily subverted. And even if we could trust the browser (which we can't), and even if it did attempt to filter stuff as you asked (which it might not), the chance of it actually verifying that that .doc file is truly a Word document is next to nil.


It should use MIME_type: For example

<input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />

this will only accept *.xlsx file type...

For the list of mime types, check the link below:
http://www.bitsandpix.com/entry/microsoft-office-2007-2010-docx-xlsx-pptx-mime-type-to-avoid-the-zip-issue/


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');
        }
    });
});


You could use JavaScript. Take in consideration that the big problem with doing this with JavaScript is to reset the input file. Well, this restricts to only JPG (for other formats you will have to change the mime type and the magic number):

<form id="form-id">
  <input type="file" id="input-id" accept="image/jpeg"/>
</form>

<script type="text/javascript">
    $(function(){
        $("#input-id").on('change', function(event) {
            var file = event.target.files[0];
            if(file.size>=2*1024*1024) {
                alert("JPG images of maximum 2MB");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            if(!file.type.match('image/jp.*')) {
                alert("only JPG images");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            var fileReader = new FileReader();
            fileReader.onload = function(e) {
                var int32View = new Uint8Array(e.target.result);
                //verify the magic number
                // for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
                if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
                    alert("ok!");
                } else {
                    alert("only valid JPG images");
                    $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                    return;
                }
            };
            fileReader.readAsArrayBuffer(file);
        });
    });
</script>

Take in consideration that this was tested on latest versions of Firefox and Chrome, and on IExplore 10.

For a complete list of mime types see Wikipedia.

For a complete list of magic number see Wikipedia.


I have made an easy way for client side validation for most cases on file filtering. It is actually quite simple. Now, before you go and try to implement this, understand that the server MUST check this file, because the javascript and HTML filtering is not a sure thing in cases where someone alters the .js, or even the HTML. I'm not including all of the actual script for the simple fact that I enjoy seeing other implement the concepts using a creative mind, but these are the steps I've taken that seem to work until I find a better answer:

Create a js object that finds the input and handles it.

Call a function, such as the OnClientUploadComplete for the AjaxControlToolKit's AsyncFileUpload control.

Inside of this function, declare a boolean variable: bIsAccepted(set to false) and string sFileName(after getting the filename from the args).

In an if..else Statement,

if(sFilename.indexOf(".(acceptedExtension1)") ||
   sFileName.indexOf(".(AcceptedExtension2)") )
{
   bIsAccepted = true;
}
else
{
   bIsAccepted = false;
}

then

if(bIsAccepted)
{
//Process Data
}

On the server, setting up a list of accepted file extensions and looping through and processing similarly will make the process cohesive and consistent, effectively allowing the UI and Code-Behind to filter the file types in almost every situation.

Given that this can be bypassed by changing the name to have a different file extension as part of the name, the mime type should also be checked before submitting to the server for further processing.

            [http://www.webmaster-toolkit.com/mime-types.shtml][1]

Hope this helps!


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


Using MVC we can restrict upload to zip files only

.HtmlAttributes(new { accept = ".zip*" })
0

精彩评论

暂无评论...
验证码 换一张
取 消