如何在不向服务器发送数据的情况下显示选定的图像? [英] How to display selected image without sending data to server?
本文介绍了如何在不向服务器发送数据的情况下显示选定的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试向客户展示他选择的图像:
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?
在onchange
中,我可以将表单发送到服务器,服务器可以将数据发回,但这真的有必要吗?客户端不能在没有乒乓的情况下向服务器显示数据吗?这是安全问题吗?
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?
推荐答案
您可以使用 FileReader 用于此的 web-api 对象,请参阅此代码段:
You can use FileReader web-api object for this, see this snippet:
HTML
<input id="src" type="file"/> <!-- input you want to read from (src) -->
<img id="target"/> <!-- image you want to display it (target) -->
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);
这篇关于如何在不向服务器发送数据的情况下显示选定的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文