Roger Gonzalez
Roger Gonzalez

Reputation: 409

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.

Upvotes: 2

Views: 7966

Answers (3)

Hackerman
Hackerman

Reputation: 12305

If you just want the name:

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

Working fiddle: https://jsfiddle.net/robertrozas/ugs6rzqx/3/

Upvotes: 4

Steven
Steven

Reputation: 121

Use

file.name

Here is your fiddle: https://jsfiddle.net/ugs6rzqx/2/

Upvotes: 3

dandavis
dandavis

Reputation: 16726

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

Upvotes: 5

Related Questions