Limit allowed file types or Get file name of selected file
I am trying to find out how to allow users to only select certain files when the file browse window opens when an input
of type file is clicked. I couldn't come up with a solution for this. Any ideas? I thought the accept
attribute would work but I didn't get much luck with that, is the below implemented correctly?
<input id="file_zip" type="file" name="file_zip" accept="zip" />
Failing with the above, I have come up with a work around of getting the file name on change so I can do checks on it but this event fires only when somethin开发者_如何转开发g changes. A user can easily select the same file and continue without firing that event again! What event can I use instead?
Any help would be great!
$('#file_zip').change(function() {
alert($('#file_zip').val());
});
you can check the file extension before the submit, here is some example code
$("#DocumentUploadForm").submit(function(data) {
//File-Extension Check - does _NOT_ replace a server-side validation
var filename = $("#FileToUpload").val()
if (filename.length == 0) { return false };
var dot = filename.lastIndexOf(".");
if (dot == -1) { return false };
var extension = filename.substr(dot, filename.length).toLowerCase();
var extensionWhitelist = new Array(".doc", ".docx", ".xls", ".xlsx",
".pdf", ".odt", ".jpg", ".gif", ".png",
".tif", ".tiff", ".jpeg");
if ($.inArray(extension, extensionWhitelist) == -1) {
alert("The file extension " + extension + " is not allowed.");
return false
};
});
but you still need to preform a server-side check, this is also the only place were you can check the acutual type of the file.
@marc.d shows a nice way of putting the check into the submit
event, which will work and not let any undesired extensions through.
If you want more advanced functionality like also filtering the "select file..." for certain file types, you could use an advanced file upload control like Flash-based SWFUpload for this. However, the way those Flash based uploads work differs slightly from a form element, you'll have to see whether it is for you.
精彩评论