如何在上传之前通过JavaScript上传预览图像

11
我想在上传图片到服务器之前预览它。我已经为此编写了一些代码,但它只能在Internet Explorer中预览,而在其他浏览器(如Safari、Chrome、Firefox)中由于某些安全原因而无法预览。有没有办法在这些浏览器中预览图片?
    <body>
       <form name="Upload" enctype="multipart/form-data" method="post">
           Filename: <INPUT type="file" id="submit">
           <INPUT type="button" id="send" value="Upload">
       </form>
       <div 
           id="div" 
           align="center" 
           style="height: 200px;width: 500px;border-style: ridge;border-color: red">
       </div>
    </body>

    <script type="text/javascript">
        var img_id=0
        var image = new Array()
        document.getElementById('send').onclick=function()
        {
            img_id++
            var id="imgid"+img_id
            image = document.getElementById('submit').value;
            document.getElementById('div').innerHTML="<img id='"+id+"' src='"+image+"' width=500px height=200px>"
        }
    </script>
</html>
8个回答

19

对于火狐浏览器,由于安全原因它会缩短路径。但是,他们提供了其他方法来完成这个任务:

var img = document.createElement("IMG");
if(document.all)
    img.src = document.getElementById('submit').value;
else
    // Your solution for Firefox.
    img.src = document.getElementById('submit').files.item(0).getAsDataURL();
document.getElementById('div').appendChild(img);

以下内容在Internet Explorer 7和Firefox 3中有效。

<style type="text/css">
    #prevImage {
        border: 8px solid #ccc;
        width: 300px;
        height: 200px;
    }
</style>
<script type="text/javascript">
    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';
    }
</script>
<pre>
     IE8 needs a security settings change: internet settings, security, custom level :

     [] Include local directory path when uploading files to a server
 ( ) Disable
 (o) Enable 
</pre>
<form>
    <input type="file" name="myImage" onchange="setImage(this);" />
</form>
<img id="prevImage" style="display:none;" />

MDC上的文件列表对象文档


@Zain 你用的是哪个版本的Chrome浏览器。 - Ramiz Uddin
@user648372,我已经更新了我的帖子。请检查<prev>标签。有一些安全设置需要更改,才能让它对您起作用。 - Ramiz Uddin
我已经在Firefox中使其正常工作,但我真的需要它能在IE和Chrome中也顺利运行。是否有其他脚本可以添加,以便它实现跨浏览器操作? - Adam Moss
它应该在IE中工作,但我仍然不确定Chrome。 - Ramiz Uddin
结果不一致。当我试图上传另一张图片时,它不会显示预览,但在某些情况下,会显示。我想这可能是一些奇怪的结果,而我对如何解决它实在没有任何头绪。 - PinoyStackOverflower
显示剩余3条评论

4

uploadFile(event: any) {
    const image: any = document.getElementById('output');
    image.src = URL.createObjectURL(event.target.files[0]);
}
<div>
    <img id="output" width="200" />
</div>
<div class="form-group">
    <label for="exampleFormControlFile1">File Input</label>
    <input type="file" (change)="uploadFile($event)" class="form-control-file" />
</div>


我已经将这个应用到我的Angular 9项目中,它完美地运行着。 - Mohammed Abir

1
“这很简单,只需要使用这个”
“在你的HTML文件中使用”
<div>
<form id="form1" runat="server">
        <input type='file' id="imgInp" />
        <br>
        <img id="blah" src="http://i.imgur.com/zAyt4lX.jpg" alt="your image" height="100" />
    </form>
<div>

在您的JavaScript文件中,只需编写以下内容。
<script>

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

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

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

    $("#imgInp").change(function(){
        readURL(this);
    });
</script>

1

请查看以下与文件API相关的链接,它适用于IE9+,我已经检查过,不适用于IE8。它展示了如何预览图像和文本文件。 http://www.xul.fr/en/html5/filereader.php FileReader,将图像加载到网页中

FileReader允许访问本地文件系统并仅使用JavaScript代码加载文档。

这完成了选择本地文件的操作,因为此标记只能将此文件的内容提供给服务器上的脚本,以及表单数据。

兼容性测试

当前浏览器是否识别包括FileReader对象在内的File API?

结果 支持File API。 测试的源代码:

<script>
if (window.File && window.FileReader && window.FileList && window.Blob) 
  document.write("<b>File API supported.</b>");
else
  document.write('<i>File API not supported by this browser.</i>');
</script>   

HTML 代码:

<input type="file" id="getimage">

<fieldset><legend>Your image here</legend>
    <div  id="imgstore"></div>
</fieldset> 

JavaScript 代码:

<script>
function imageHandler(e2) 
{ 
  var store = document.getElementById('imgstore');
  store.innerHTML='<img src="' + e2.target.result +'">';
}

function loadimage(e1)
{
  var filename = e1.target.files[0]; 
  var fr = new FileReader();
  fr.onload = imageHandler;  
  fr.readAsDataURL(filename); 
}

window.onload=function()
{
  var x = document.getElementById("filebrowsed");
  x.addEventListener('change', readfile, false);
  var y = document.getElementById("getimage");
  y.addEventListener('change', loadimage, false);
}
</script>

1

在我的FF 3.6、IE 8、Safari 4.0和Chrome 3.195中,这对我来说很好用。

一些样式指针:

  • 不要使用固定宽度的预览区域,你的图片将会被扭曲以适应该区域
  • 使用这个而不是document.getElementById():

    function $(id) { return document.getElementById(id); }

  • 例如: $('send')


Steve,你能否给我解释一下这个函数 $(id) { return document.getElementById(id); } 的意思吗?非常感谢。 - Zain
1
@Zain他提供了一种使用'document.getElementById()'的速记方式。它很冗长,因此'$()'快捷方式很有帮助。 - alex
1
使用“$”符号可能会与广泛使用的jQuery库造成混淆。 - ImportError

1

除非使用新的文件API,否则无法在上传之前获取用户文件:

示例:显示用户选择的图像缩略图

当然,这不会跨浏览器。也可能有一种通过Flash和数据URL(或仅在Flash中预览)来完成它的方法,但我更喜欢避免JavaScript<-> Flash集成。


谢谢Pradeep和theazureshadow的帮忙,但是我很难相信我们不能在浏览器(FF、基于Webkit的)中打开图片。请查看'Mugtug'公司的网络应用程序Darkroom(http://mugtug.com/darkroom/)。这个网络应用程序允许用户加载一个图像进行进一步操作 (位于网络应用程序左上角的打开图标),我想要实现相同的弹出对话框功能,让用户可以选择要显示的图像。您有什么想法吗? - Zain
就像我说的那样,你可以使用HTML5来完成它。这就是Mugtug的做法:Mugtug Darkroom是一款完全由HTML5驱动的基于浏览器的照片编辑器 - theazureshadow

0

如果输入类型是文件,那么使用htmlfilereader函数可以预览HTML页面吗?使用accept type ="text/html"

我得到了文件的描述和大小...

<script>
  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // files is a FileList of File objects. List some properties.
    var output = [];
    for (var i = 0, f; f = files[i]; i++) {
      output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
                  f.size, ' bytes, last modified: ',
                  f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
                  '</li>');
    }
    document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>

上述问题与离线本地存储的HTML页面有关。我们可以使用实时URL预览实时页面。

<html>
    <head>
    <!--[if IE]>
    <style>
    #frame {
        zoom: 0.2;
    }
    </style>
    <![endif]-->
    <style>
    #frame {
        width: 800px;
        height: 520px;
        border: none;
        -moz-transform: scale(0.2);
        -moz-transform-origin: 0 0;
        -o-transform: scale(0.2);
        -o-transform-origin: 0 0;
        -webkit-transform: scale(0.2);
        -webkit-transform-origin: 0 0;
    }
    </style>
    </head>
    <body>
    <iframe id="frame" src="http://www.bing.com">
    </iframe>
    </body>
    </html

>


-1

这在FF 3.6、IE 9、Safari 4.0和Chrome 3.195中都可以正常工作。

var reader = new FileReader();

function preview(what) {
     if(jQuery.browser.msie || jQuery.browser.safari || jQuery.browser.chrome) {
         document.getElementById("preview-photo").src=what.value;
         return;
    }
    else{                   
        // array with acceptable file types
        var accept = ["image/png","image/jpeg","image/jpg","image/gif"];

        // if we accept the first selected file type
        if (accept.indexOf(what.files[0].type) > -1) {
            if(what.files && what.files[0]){
                  reader.readAsDataURL(what.files[0]);
                  document.getElementById("preview-photo").src=reader.result;
            }
        }       
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接