好吧,我正在尝试使用File API和jQuery显示图像缩略图。我已经阅读了大量来自Google搜索的教程,以及我读过的代码应该有效:
$(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>
然而,它正在返回此错误:
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
关于我做错了什么的想法?
答案 0 :(得分:1)
更改:
uploadAvatar($(this).files[0]);
为:
uploadAvatar(this.files[0]);
jQuery对象没有files
属性。
答案 1 :(得分:1)
files
是文件输入元素本身的属性,而不是jQuery对象,使用uploadAvatar(this.files[0]);
代替uploadAvatar($(this).files[0]);
答案 2 :(得分:1)
阅读文件是一种浪费。 Base64编码会在文件大小上产生33%的开销。
相反,只需从文件对象创建一个blob:
URL即可。效率更高:
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]);
});