Trezy
Trezy

Reputation: 121

Can't retrieve files from File API

Alright, I'm trying to display an image thumbnail using the File API and jQuery. I've read a ton of tutorials from my Google search and from what I've read this code should work:

Javascript

$(document).ready(function(){
    function uploadAvatar( file ) {
        var preview = $('#newUserProfile .avatar img');
        var reader = new FileReader();

        reader.onload = function(e){
            preview.attr('src', e.target.result);
        };

        reader.readAsDataURL(file);
    }

    $('input#imageUpload').change(function(){
        uploadAvatar($(this).files[0]);
    });
});

HTML

<form>
    <input type="file" id="imageUpload" />
</form>
<div id="newUserProfile">
    <div class="avatar">
        <img src="" />
    </div>
</div>

However, it's returning this error:

Uncaught TypeError: Cannot read property '0' of undefined    -> newUser.js
  (anonymous function)                                       -> newUser.js
  p.event.dispatch                                           -> jquery.min.js
  g.handle.h                                                 -> jquery.min.js

Any ideas as to what I'm doing wrong?

Upvotes: 2

Views: 1486

Answers (3)

ebidel
ebidel

Reputation: 24119

Reading the file is a waste. Base64 encoding creates 33% overhead on the files size. Instead, just create a blob: URL from it the file object. It's more efficient:

window.URL = window.URL || window.webkitURL;

function uploadAvatar(file) {
  var url = window.URL.createObjectURL(file);
  $('#newUserProfile .avatar img').attr('src', url);
}

$('input#imageUpload').change(function(){
  uploadAvatar(this.files[0]);
});

Upvotes: 1

Musa
Musa

Reputation: 97727

files is a property of the file input element itself not the jQuery object, use uploadAvatar(this.files[0]); instead of uploadAvatar($(this).files[0]);

Upvotes: 1

Ram
Ram

Reputation: 144739

Change:

uploadAvatar($(this).files[0]);

to:

uploadAvatar(this.files[0]);

jQuery object has no files property.

Upvotes: 1

Related Questions