Access multiple files using Jquery
I am using HTML 5 Multiple files ability to select multiple files for upload. The files come as an array of files in the $_FILES
variable. I want to use jQuery to get all the names of the files listed before upload button is clicked.
<input class="pictures-upload" name="multiplePhotos[]" type="file" multiple="multiple" /&开发者_开发百科gt;
I want to append a onchange event that when a person clicks the upload files and selects multiple files, it will take names of all files and append it on the body of html. I am using
$('.upload_button').live('change', function () {
var li = $('<li />').text($(this).val()),
$('#body').append(li);
});
This takes only the last file to be selected. How do I get all the files?
The input element has a native property of 'files' which is a FileList type (i.e. a sequence of File). If you have a look at the W3 spec for the File element, you'll discover what properties you can access.
However, long story short, the jQuery val method won't return what you want. Since 'files' is a native property of the input element, you can access it directly using this.files
. Then just iterate over the array to get the File objects that you can get get the information for (name, size, type, etc).
for (var i = 0; i < this.files.length; i++) {
var file = this.files[i];
$fileList.append('<li>' + file.name + '</li>');
}
Look here for the jsFiddle of it: http://jsfiddle.net/jonathon/bdbXk/
精彩评论