javascript 如何在不向服务器发送数据的情况下显示选定的图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17138244/
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 selected image without sending data to server?
提问by revolver
I am trying to show the client an image which he has selected:
我试图向客户展示他选择的图像:
<input type="file" onchange="showImage(this)"/>
But I can't read the value of the input, as I checked out here. Is it possible to display the image?
但是我无法读取输入的值,因为我在这里签出。可以显示图像吗?
In onchange
I can send the form to server and server can send the data back, but is it really necessary? Can't the client display the data without the ping-pong to the server? Is it a security issue?
在onchange
我可以将表单发送到服务器,服务器可以将数据发回,但这真的有必要吗?客户端不能在没有乒乓的情况下向服务器显示数据吗?这是一个安全问题吗?
回答by Jan Turoň
You can use FileReaderweb-api object for this, see this snippet:
您可以为此使用FileReaderweb-api 对象,请参阅此代码段:
the HTML
HTML
<input id="src" type="file"/> <!-- input you want to read from (src) -->
<img id="target"/> <!-- image you want to display it (target) -->
the javascript
javascript
function showImage(src,target) {
var fr=new FileReader();
// when image is loaded, set the src of the image where you want to display it
fr.onload = function(e) { target.src = this.result; };
src.addEventListener("change",function() {
// fill fr with image data
fr.readAsDataURL(src.files[0]);
});
}
var src = document.getElementById("src");
var target = document.getElementById("target");
showImage(src,target);