如何在使用 JavaScript 或 jquery 上传之前预览图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6870943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:09:29  来源:igfitidea点击:

How to preview a image before upload using JavaScript or jquery?

javascriptjqueryinternet-explorergoogle-chrome

提问by Peeyush

I just need to display the image chosen (Browse) by the user before the upload. For this purpose i am using this code:

我只需要在上传之前显示用户选择(浏览)的图像。为此,我正在使用此代码:

JS

JS

function setImage(file) {
    if(document.all)
        document.getElementById('prevImage').src = file.value;
    else
        document.getElementById('prevImage').src = file.files.item(0).getAsDataURL();
    if(document.getElementById('prevImage').src.length > 0) 
        document.getElementById('prevImage').style.display = 'block';
}

HTML

HTML

<img id="prevImage"  src=""  alt="" width="313" height="315" />
<input name="photo1" id="photo1" type="file" onchange="setImage(this);"  value="" class="input" size="17"/>

This code working fine in Safari, Firefox 3,4,5 but doesn't work in Google Chrome 12 or higher and IE 8, 9.

此代码在 Safari、Firefox 3、4、5 中运行良好,但在 Google Chrome 12 或更高版本和 IE 8、9 中不起作用。

So please tell me any solution regarding this issues?

所以请告诉我有关此问题的任何解决方案?

I already tried other solution given on this website but they are also not working in all major browsers.

我已经尝试过本网站上给出的其他解决方案,但它们也不适用于所有主要浏览器。

if you have a solution for this code or a completely new code then please tell me.

如果您有此代码的解决方案或全新的代码,请告诉我。

采纳答案by Awea

I find a complete solution from another stack post, hereis the solution.

我从另一个堆栈帖子中找到了一个完整的解决方案,是解决方案。

回答by giuseppe

You can also use FileReaderwhich is a standard Web API now.

您现在还可以使用FileReader,它现在是一个标准的 Web API。