Reputation: 121
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:
$(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]);
});
});
<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
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
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
Reputation: 144739
Change:
uploadAvatar($(this).files[0]);
to:
uploadAvatar(this.files[0]);
jQuery object has no files
property.
Upvotes: 1