我正在使用VueJS进行文件上传图像预览,但遇到了以下问题: 1.-用户上传文件 2.-在输入字段旁边显示预览 3.-输入字段现在显示,尽管有预览,但没有上传图片。
这是html:
<input type='file' accept='image/*' @change="onChange" name='file' />
<img width='200' :src="uploadPreview" alt='preview' />
这是我的vueJs代码:
data: function() { return {
uploadPreview : "",
}
},
methods : {
onChange(e) {
if (! e.target.files.length) return;
let file = e.target.files[0];
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = e => {
this.uploadPreview = e.target.result; // if this line is commented out or just not present, the upload will work but the preview won't show since uploadPreview does not have a value set.
};
},
}
我在代码中对此行进行了注释。
this.uploadPreview = e.target.result;
如果此行已被注释掉或不存在,则上传将起作用,但预览不会显示,因为uploadPreview没有设置值。
为什么这不起作用?在将uploadPreview
设置为一些二进制图像数据后,为什么会重置文件的输入字段值?再一次把我的头撞在桌子上。
答案 0 :(得分:0)
我建议您调试点。尝试让我知道。
data: function() { return {
uploadPreview : "ABCD",
}
},
methods : {
onChange(e) {
if (! e.target.files.length) return;
let file = e.target.files[0];
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = e => {
console.log("FIRST SEE WHAT'S INSIDE THE RESULTS",e.target.result);
console.log("SECOND MAKE SURE YOU CAN ACCESS",this.uploadPreview) // this should print ABCD
this.uploadPreview = e.target.result; // if this line is commented out or just not present, the upload will work but the preview won't show since uploadPreview does not have a value set.
};
},
}
最后
<img width='200' :src="uploadPreview" :alt='uploadPreview' />
(alt应该等于图像数据)