【问题标题】:How to display an image from a file input? [duplicate]如何显示来自文件输入的图像? [复制]
【发布时间】:2014-04-10 07:20:18
【问题描述】:

我想选择一个文件并在浏览器上显示图像。 我尝试插入直接图像路径并且它有效。

现在的问题是,如何显示来自<input type=file> 的图像?

我的代码如下所示:

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>

【问题讨论】:

  • 您创建了FileReader(),但它如何知道要读取什么文件?
  • 所以我必须把它写成FileReader(file)?
  • 图像宽度和高度是 (BTW) 只读的。您可以改用var image = new Image(w, h);

标签: javascript


【解决方案1】:
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/ 工作示例

【讨论】:

  • 我需要一些&lt;img src&gt;吗?还是什么?
  • 我试过了,它奏效了。谢谢:)
  • 简单易行。谢谢
【解决方案2】:

小心点:reader.onloadend = function { 必须是 reader.onloadend = function() {

但是为什么要使用 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);
}

然后就这样称呼它: 显示

【讨论】:

  • 你有任何工作样本吗?我尝试使用它,但它不起作用。
  • 我将它用于我的应用程序谁在这里:test.projet1.worldheberg.com/local/fr-appli-test.html(所有图像都不在服务器中,这就是为什么你可以显示一些丢失的图像)你能发布你的链接吗?
  • 如果文件在客户的机器上,你从哪里得到 imgSRC。这基本上向 DOM 添加了一个 img 元素(非常简单)。问题是如何显示来自文件输入的图像,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多