【问题标题】:Grab image from input field to get image data / display image从输入字段抓取图像以获取图像数据/显示图像
【发布时间】:2011-09-10 15:16:08
【问题描述】:

我一直在环顾四周,无法找到这是否可能。

这是我在提交之前希望发生的事情:当用户选择要上传的文件时,我想抓取图像的数据并将其转换为 base64。转换完成后,我想直接显示在div中,或者通过AJAX发送到服务器,然后显示在div中。

下面基本上是我要找的:

// index.php
<input type="file" name="img" id="img" onChange="displayImg(this)">

// displayImg.js
function displayImg(img) {
   imgData = img.?;  // How do I do this?
   img64 =           // I know how to do this.
   document.write("<img src='data:image/jpeg;base64,"+img64+"' />");
}

【问题讨论】:

    标签: javascript html ajax file-upload onchange


    【解决方案1】:
    function displayImage(evt){
      var files = evt.target.files;
      var reader = new FileReader();
    
      reader.onload = function(frEvent) {
          document.getElementById("renderImage").innerHTML = '<img src="'+frEvent.target.result+'" />';
      }
      reader.readAsDataURL(files[0]);
    }
    

    上面的代码对我有用。它缺乏验证和所有好东西,但这对你来说应该是一个很好的起点。

    【讨论】:

    • “作品”在哪些浏览器中?未来继续“工作”的可能性有多大?
    • 我已经测试了我的代码版本,它可以在 Firefox、Chrome 和 Opera 中运行。它在IE中不起作用,并且Safari返回“ReferenceError:找不到变量:FileReader”的错误
    • 我需要将 "reader.onload(function(theFile){" 更改为 "reader.onload=(function(theFile){" 才能工作
    猜你喜欢
    • 1970-01-01
    • 2019-07-26
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    相关资源
    最近更新 更多