Javascript 在上传之前预览图像

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

Preview an image before it is uploaded

javascriptjqueryfile-upload

提问by Simbian

I want to be able to preview a file (image) before it is uploaded. The preview action should be executed all in the browser without using Ajax to upload the image.

我希望能够在上传之前预览文件(图像)。预览动作应该全部在浏览器中执行,不使用 Ajax 上传图像。

How can I do this?

我怎样才能做到这一点?

回答by Ivan Baev

Please take a look at the sample code below:

请看下面的示例代码:

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]); // convert to base64 string
  }
}

$("#imgInp").change(function() {
  readURL(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form runat="server">
  <input type='file' id="imgInp" />
  <img id="blah" src="#" alt="your image" />
</form>

Also, you can try this sample here.

此外,您可以在此处尝试此示例

回答by nkron

There are a couple ways you can do this. The most efficient way would be to use URL.createObjectURL()on the Filefrom your <input>. Pass this URL to img.srcto tell the browser to load the provided image.

有几种方法可以做到这一点。最有效的方法是使用URL.createObjectURL()文件从你的<input> 。将此 URL 传递给img.src以告诉浏览器加载提供的图像。

Here's an example:

下面是一个例子:

<input type="file" accept="image/*" onchange="loadFile(event)">
<img id="output"/>
<script>
  var loadFile = function(event) {
    var output = document.getElementById('output');
    output.src = URL.createObjectURL(event.target.files[0]);
    output.onload = function() {
      URL.revokeObjectURL(output.src) // free memory
    }
  };
</script>

You can also use FileReader.readAsDataURL()to parse the file from your <input>. This will create a string in memory containing a base64 representation of the image.

您还可以使用FileReader.readAsDataURL()来解析 <input> 中的文件。这将在内存中创建一个包含图像的 base64 表示的字符串。

<input type="file" accept="image/*" onchange="loadFile(event)">
<img id="output"/>
<script>
  var loadFile = function(event) {
    var reader = new FileReader();
    reader.onload = function(){
      var output = document.getElementById('output');
      output.src = reader.result;
    };
    reader.readAsDataURL(event.target.files[0]);
  };
</script>

回答by cnlevy

One-liner solution:

单线解决方案:

The following code uses object URLs, which is much more efficient than data URL for viewing large images (A data URL is a huge string containing all of the file data, whereas an object URL, is just a short string referencing the file data in-memory):

下面的代码使用对象 URL,它在查看大图像时比数据 URL 更有效(数据 URL 是一个包含所有文件数据的巨大字符串,而对象 URL 只是一个引用文件数据的短字符串 -记忆):

<img id="blah" alt="your image" width="100" height="100" />

<input type="file" 
    onchange="document.getElementById('blah').src = window.URL.createObjectURL(this.files[0])">

Generated URL will be like:

生成的 URL 将类似于:

blob:http%3A//localhost/7514bc74-65d4-4cf0-a0df-3de016824345

回答by Dmitri Dmitri

The answer of LeassTaTT works well in "standard" browsers like FF and Chrome. The solution for IE exists, but looks different. Here description of cross-browser solution:

LeassTaTT 的答案在 FF 和 Chrome 等“标准”浏览器中运行良好。IE 的解决方案存在,但看起来不同。这里是跨浏览器解决方案的描述:

In HTML we need two preview elements, img for standard browsers and div for IE

在 HTML 中,我们需要两个预览元素,标准浏览器的 img 和 IE 的 div

HTML:

HTML:

<img id="preview" 
     src="" 
     alt="" 
     style="display:none; max-width: 160px; max-height: 120px; border: none;"/>

<div id="preview_ie"></div>

In CSS we specify the following IE specific thing:

在 CSS 中,我们指定了以下 IE 特定的东西:

CSS:

CSS:

#preview_ie {
  FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)
}  

In HTML we include the standard and the IE-specific Javascripts:

在 HTML 中,我们包含标准和特定于 IE 的 Javascript:

<script type="text/javascript">
  {% include "pic_preview.js" %}
</script>  
<!--[if gte IE 7]> 
<script type="text/javascript">
  {% include "pic_preview_ie.js" %}
</script>

The pic_preview.jsis the Javascript from the LeassTaTT's answer. Replace the $('#blah')whith the $('#preview')and add the $('#preview').show()

pic_preview.js是 LeassTaTT 答案中的 Javascript。替换 $('#blah')whith$('#preview')并添加$('#preview').show()

Now the IE specific Javascript (pic_preview_ie.js):

现在是特定于 IE 的 Javascript (pic_preview_ie.js):

function readURL (imgFile) {    
  var newPreview = document.getElementById('preview_ie');
  newPreview.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = imgFile.value;
  newPreview.style.width = '160px';
  newPreview.style.height = '120px';
}    

That's is. Works in IE7, IE8, FF and Chrome. Please test in IE9 and report. The idea of IE preview was found here: http://forums.asp.net/t/1320559.aspx

那是。适用于 IE7、IE8、FF 和 Chrome。请在IE9中测试并报告。IE预览的想法在这里找到:http: //forums.asp.net/t/1320559.aspx

http://msdn.microsoft.com/en-us/library/ms532969(v=vs.85).aspx

http://msdn.microsoft.com/en-us/library/ms532969(v=vs.85).aspx

回答by Sachin Prasad

I have edited @Ivan's answer to display "No Preview Available" image, if it is not an image:

我已经编辑了@Ivan 的答案以显示“无可用预览”图像,如果它不是图像:

function readURL(input) {
    var url = input.value;
    var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
    if (input.files && input.files[0]&& (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) {
        var reader = new FileReader();

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

        reader.readAsDataURL(input.files[0]);
    }else{
         $('.imagepreview').attr('src', '/assets/no_preview.png');
    }
}

回答by Nino ?kopac

Here's a multiple filesversion, based on Ivan Baev's answer.

这是一个多文件版本,基于 Ivan Baev 的回答。

The HTML

HTML

<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>

JavaScript / jQuery

JavaScript / jQuery

$(function() {
    // Multiple images preview in browser
    var imagesPreview = function(input, placeToInsertImagePreview) {

        if (input.files) {
            var filesAmount = input.files.length;

            for (i = 0; i < filesAmount; i++) {
                var reader = new FileReader();

                reader.onload = function(event) {
                    $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
                }

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

    };

    $('#gallery-photo-add').on('change', function() {
        imagesPreview(this, 'div.gallery');
    });
});

Requires jQuery 1.8 due to the usage of $.parseHTML, which should help with XSS mitigation.

由于使用了 $.parseHTML,因此需要 jQuery 1.8,这应该有助于缓解 XSS。

This will work out of the box, and the only dependancy you need is jQuery.

这将是开箱即用的,您需要的唯一依赖是 jQuery。

回答by Md. Rahman

Yes. It is possible.

是的。有可能的。

Html

html

<input type="file" accept="image/*"  onchange="showMyImage(this)" />
 <br/>
<img id="thumbnil" style="width:20%; margin-top:10px;"  src="" alt="image"/>

JS

JS

 function showMyImage(fileInput) {
        var files = fileInput.files;
        for (var i = 0; i < files.length; i++) {           
            var file = files[i];
            var imageType = /image.*/;     
            if (!file.type.match(imageType)) {
                continue;
            }           
            var img=document.getElementById("thumbnil");            
            img.file = file;    
            var reader = new FileReader();
            reader.onload = (function(aImg) { 
                return function(e) { 
                    aImg.src = e.target.result; 
                }; 
            })(img);
            reader.readAsDataURL(file);
        }    
    }

You can get Live Demofrom here.

您可以从这里获得现场演示

回答by Sivashanmugam Kannan

Clean and simple JSfiddle

干净简单的 JSfiddle

This will be useful when you want The event to triggered indirectly from a div or a button.

当您希望从 div 或按钮间接触发事件时,这将很有用。

<img id="image-preview"  style="height:100px; width:100px;"  src="" >

<input style="display:none" id="input-image-hidden" onchange="document.getElementById('image-preview').src = window.URL.createObjectURL(this.files[0])" type="file" accept="image/jpeg, image/png">

<button  onclick="HandleBrowseClick('input-image-hidden');" >UPLOAD IMAGE</button>


<script type="text/javascript">
function HandleBrowseClick(hidden_input_image)
{
    var fileinputElement = document.getElementById(hidden_input_image);
    fileinputElement.click();
}     
</script>

回答by Ratan Paul

Example with multiple images using JavaScript (jQuery) and HTML5

使用 JavaScript (jQuery) 和 HTML5 包含多个图像的示例

JavaScript (jQuery)

JavaScript (jQuery)

function readURL(input) {
     for(var i =0; i< input.files.length; i++){
         if (input.files[i]) {
            var reader = new FileReader();

            reader.onload = function (e) {
               var img = $('<img id="dynamic">');
               img.attr('src', e.target.result);
               img.appendTo('#form1');  
            }
            reader.readAsDataURL(input.files[i]);
           }
        }
    }

    $("#imgUpload").change(function(){
        readURL(this);
    });
}

Markup (HTML)

标记 (HTML)

<form id="form1" runat="server">
    <input type="file" id="imgUpload" multiple/>
</form>

回答by Muhammad Awais

Following is the working code.

以下是工作代码。

<input type='file' onchange="readURL(this);" /> 
<img id="ShowImage" src="#" />

Javascript:

Javascript:

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

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

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