Search code examples
javascriptjqueryhtmlmulti-upload

How can I get the filename from the FileReader function in a Multiple Input?


I have the following code:

<input type="file" multiple='multiple'>
<div id="thumbs"></div>

<script type="text/javascript">
    $('input[type="file"]').change(function() {
    $('#thumbs').html('');
    $.each(this.files, function() {
    readURL(this);
 })
});

function readURL(file) {
    var reader = new FileReader();
    reader.onload = function(e) {
    $('#thumbs').append('<img src="' + e.target.result + '" width="20%">')
    $('#quantity').text(i)
  }
  reader.readAsDataURL(file);
}
</script>

This is a multiupload input. When I select 'x' pictures, it creates thumbnails for them. That works perfectly, but I want to know how can I get the files name (if a picture is named "sun.jpg", I want to get "sun"), and append them bellow to the picture. I've tried this:

$('#thumbs').append('<img src="' + e.target.result + '" width="20%"><p>'+e.name+'</p>')

But e.name is undefined.

Here is a fiddle of everything: https://jsfiddle.net/ugs6rzqx/1/

Any help would be appreciated. Thanks.


Solution

  • FileReader's event object is slim on details about the file. Inside the callback you can reach the normal File object, which still has all the file meta information like name, date, and size.

    Your code just needs to use file instead of e

    $('#thumbs').append('<img src="' + e.target.result + '" width="20%"><p>'+file.name+'</p>')