javascript 如何显示来自文件输入的图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22245100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to display an image from a file input?
提问by user3335903
I would like to choose a file and display the image on the browser. I tried inserting the direct image path and it worked.
我想选择一个文件并在浏览器上显示图像。我尝试插入直接图像路径并且它起作用了。
The problem now is, how can I display the image from the <input type=file>
?
现在的问题是,如何从<input type=file>
?
Here is what my code looks like:
这是我的代码的样子:
function myFunction() {
var file = document.getElementById('file').files[0];
var reader = new FileReader();
reader.onloadend = function {
var image = document.createElement("img");
image.src = "reader"
image.height = 200;
image.width = 200;
document.body.appendChild(image);
}
}
<input type=file name=filename id=file>
<button type=button onclick='myFunction()'>Display</button>
回答by Nephelococcygia
function myFunction() {
var file = document.getElementById('file').files[0];
var reader = new FileReader();
// it's onload event and you forgot (parameters)
reader.onload = function(e) {
var image = document.createElement("img");
// the result image data
image.src = e.target.result;
document.body.appendChild(image);
}
// you have to declare the file loading
reader.readAsDataURL(file);
}
http://jsfiddle.net/Bwj2D/11/working example
回答by daarksim
be carrefull : reader.onloadend = function { must be reader.onloadend = function() {
小心: reader.onloadend = function { 必须是 reader.onloadend = function() {
but why use a fileReader ? For exemple my function to add pictures in my webSite =>
但是为什么要使用 fileReader 呢?例如,我在网站中添加图片的功能 =>
function createImageBase(src, alt) {
var image = document.createElement('img');
image.src = src;
image.alt = alt;
return image;
}
function addPicture(targetID, imageSRC){
var location = document.getElementById(targetID);
var image = createImageBase(imageSRC, imageSRC);
location.appendChild(image);
}
Then just call it like that : Display
然后就这样称呼它:显示