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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4094012/
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-08-23 10:35:13  来源:igfitidea点击:

How to upload preview image before upload through JavaScript

javascript

提问by Zain

I want to preview an image before uploading it to the server. I have written a little bit code for it, but it is only being previewed in Internet Explorer, not in other browsers like Safari, Chrome, Firefox, due to some type of security reasons. Is there any solution to preview the image in these browsers?

我想在将图像上传到服务器之前预览图像。我为它编写了一些代码,但由于某种类型的安全原因,它只能在 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>

回答by Ramiz Uddin

For Firefox. Because of security it has a truncated path. However, they have provided other ways of doing this:

对于火狐。为了安全起见,它有一条截断的路径。但是,他们提供了其他方法来做到这一点:

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

The below is working in Internet Explorer 7 and Firefox 3.

以下适用于 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;" />

Documentation of File List object on MDC

MDC 上文件列表对象的文档

回答by theazureshadow

It's not possible to grab a user file before upload, except using the new File API:

上传前无法获取用户文件,除非使用新的 File API:

Example: Showing thumbnails of user-selected images

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

This will not, of course, be cross-browser. There might also be a way to do it via Flash and data URLs (or just previewing in Flash), but I prefer to avoid JavaScript <-> Flash integration.

当然,这不会是跨浏览器的。可能还有一种方法可以通过 Flash 和数据 URL(或仅在 Flash 中预览)来实现,但我更愿意避免 JavaScript <-> Flash 集成。

回答by saeed

just have a look on following link related on file API, it works for IE9+ i checked it does not work for IE8 it shows how to preview image and text files http://www.xul.fr/en/html5/filereader.phpFileReader, loading an image in a webpage

只需查看与文件 API 相关的以下链接,它适用于 IE9+ 我检查它不适用于 IE8 它显示了如何预览图像和文本文件 http://www.xul.fr/en/html5/filereader.phpFileReader,在网页中加载图像

FileReader allows access to the local file system and load documents with just JavaScript code.

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

This completes the for selecting local file, as this tag can only provide the content of this file to a script on the server, with the form data.

这样就完成了选择本地文件,因为这个标签只能将这个文件的内容和表单数据一起提供给服务器上的脚本。

Compatibility test

兼容性测试

The current browser recognizes it the File API, which includes the FileReader object?

当前浏览器识别它的 File API,其中包括 FileReader 对象?

Result File API supported. Source code of the test:

支持结果文件 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 code:

HTML代码:

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

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

JavaScript code:

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>

回答by Ben

This works fine for me in FF 3.6, IE 8, Safari 4.0, and Chrome 3.195.

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

A few style pointers though:

一些样式指针虽然:

  • Don't use a fixed-width preview area, your picture will be distorted to fit the area
  • Instead of document.getElementById()use this:

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

  • Example: $('send')

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

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

  • 例子: $('send')

回答by shailendra pathak

if input type is file then using htmlfilereader function can we see the preview of html page? using accept type ="text/html"

如果输入类型是文件,那么使用 htmlfilereader 函数我们可以看到 html 页面的预览吗?使用接受类型 ="text/html"

i got the file description and size...

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

<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>

above mention problem is related with offline local stored html pages. we can see the preview of live page using live url as-

上面提到的问题与离线本地存储的 html 页面有关。我们可以使用实时网址查看实时页面的预览 -

<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

>

>

回答by Abhijit Chakra

It's Simple just use this

这很简单,只需使用这个

In your HTML file use

在您的 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>

And inside your java script file just write this

在你的java脚本文件中写下这个

<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>

回答by srinivas

This works fine in FF 3.6, IE 9, Safari 4.0, and Chrome 3.195.

这适用于 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;
            }
        }       
    }
}