如何在 html 和 javascript 中显示用户上传的照片

How to display a photo uploaded by user in html and javascript

我想知道如何使用 html 和 javascript 显示用户上传到网站上的照片。我尝试使用我在另一个 Whosebug 问题上找到的代码,但它对我不起作用。这是我在 chrome、firefox 和 safari 中试过的代码。 感谢任何帮助

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>

Javascript:

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

您可以简单地使用纯 JS 来实现它。

function handleImageUpload() 
{

var image = document.getElementById("upload").files[0];

    var reader = new FileReader();

    reader.onload = function(e) {
      document.getElementById("display-image").src = e.target.result;
    }

    reader.readAsDataURL(image);

} 
<input id="upload" type="file" onChange="handleImageUpload()" />
<img id="display-image" src="" />

你的代码工作正常,我已经测试过了。

我想你忘了 link javascript 到你的 HTML 源代码。

请检查下面的代码片段,我已经在 Google chrome 版本 66.0.3359.117(官方构建)(64 位)上进行了测试,它工作正常。

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]);
    }
}
<!DOCTYPE html>
<html>

<head>
    
    <meta charset=utf-8 />
    <title>JS Bin</title>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
    <!--[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>