【问题标题】:How to display selected image without sending data to server?如何在不向服务器发送数据的情况下显示所选图像?
【发布时间】:2024-04-26 13:15:01
【问题描述】:

我正在尝试向客户展示他选择的图像:

<input type="file" onchange="showImage(this)"/>

但我无法读取输入的值,因为我检查了here。可以显示图片吗?

onchange我可以将表单发送到服务器,服务器可以将数据发送回来,但是真的有必要吗?客户端不能在没有乒乓球的情况下向服务器显示数据吗?是安全问题吗?

【问题讨论】:

  • 如果您以这种方式提交表单,那么是的——与服务器的乒乓球是不可避免的。您可以使用 HTML5 File API 从本地文件系统加载图像并显示它。

标签: javascript html file-io


【解决方案1】:

您可以为此使用FileReader web-api 对象,请参阅此 sn-p:

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);

【讨论】:

  • 查看链接。它应该适用于所有主流浏览器以及自 IE10 起。
  • 代码中的var input=this 什么都不做。 input 变量从未使用过。
  • HTML cmets 是 &lt;!-- --&gt; 而不是 //
最近更新 更多