Search code examples
jqueryhtmlfileapi

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?


Solution

  • 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]);