HTML - 选择文件名后显示图像

时间:2012-09-11 11:41:49

标签: html file-upload

  

可能重复:
  Preview an image before it is uploaded

我有一张允许我使用

的表格
<input type="file" name="filename" accept="image/gif, image/jpeg, image/png">

浏览并选择一个文件。

我想要做的是在选择图像后立即显示该图像。 这是在表单上的“提交”按钮被按下之前,因此图像几乎肯定存在于客户端。可以这样做吗?

3 个答案:

答案 0 :(得分:253)

你走了:

<强> HTML

<!DOCTYPE html>
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>
  <input type='file' onchange="readURL(this);" />
    <img id="blah" src="#" alt="your image" />
</body>
</html>

<强>脚本:

function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah')
                    .attr('src', e.target.result)
                    .width(150)
                    .height(200);
            };

            reader.readAsDataURL(input.files[0]);
        }
    }

Live Demo

答案 1 :(得分:27)

您可以使用以下代码实现此目的:

$("input").change(function(e) {

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {

        var file = e.originalEvent.srcElement.files[i];

        var img = document.createElement("img");
        var reader = new FileReader();
        reader.onloadend = function() {
             img.src = reader.result;
        }
        reader.readAsDataURL(file);
        $("input").after(img);
    }
});

演示: http://jsfiddle.net/ugPDx/

答案 2 :(得分:3)

这可以使用HTML5完成,但只能在支持它的浏览器中使用。这是一个example

请记住,对于不支持此功能的浏览器,您需要一种替代方法。我在this plugin取得了很大的成功,这需要你手中的很多工作。

相关问题