如何显示来自文件输入的图像?

use*_*903 4 javascript

我想选择一个文件并在浏览器中显示图像。我尝试插入直接图像路径,它起作用了。

现在的问题是,如何显示图像<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);
    }
}
Run Code Online (Sandbox Code Playgroud)
<input type=file name=filename id=file>
<button type=button onclick='myFunction()'>Display</button>
Run Code Online (Sandbox Code Playgroud)

Nep*_*gia 7

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);
 }
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/Bwj2D/11/工作示例