如何使用jQuery在弹出窗口中预览输入类型="文件"中的所选图像?

Pra*_*sad 59 jquery html5

在我的代码中,我允许用户上传图像.现在我想在同一个弹出窗口中将此选定图像显示为预览.我怎么能用jQuery做到这一点?

以下是我在弹出窗口中使用的输入类型.

HTML代码:

<input type="file" name="uploadNewImage">
Run Code Online (Sandbox Code Playgroud)

Pra*_*pan 154

演示

HTML:

 <form id="form1" runat="server">
   <input type='file' id="imgInp" />
   <img id="blah" src="#" alt="your image" />
</form>
Run Code Online (Sandbox Code Playgroud)

jQuery的

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);
});
Run Code Online (Sandbox Code Playgroud)

参考

  • IE9或IE8不支持,但除此之外它还有很好的支持... http://caniuse.com/#feat=filereader (2认同)

san*_*ngh 34

如果您使用的是HTML5,请尝试使用以下代码段

<img id="uploadPreview" style="width: 100px; height: 100px;" />
<input id="uploadImage" type="file" name="myPhoto" onchange="PreviewImage();" />
<script type="text/javascript">

    function PreviewImage() {
        var oFReader = new FileReader();
        oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);

        oFReader.onload = function (oFREvent) {
            document.getElementById("uploadPreview").src = oFREvent.target.result;
        };
    };

</script>
Run Code Online (Sandbox Code Playgroud)


Abd*_*ost 14

您可以使用 URL.createObjectURL

    function img_pathUrl(input){
        $('#img_url')[0].src = (window.URL ? URL : webkitURL).createObjectURL(input.files[0]);
    }
Run Code Online (Sandbox Code Playgroud)
#img_url {
  background: #ddd;
  width:100px;
  height: 90px;
  display: block;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="" id="img_url" alt="your image">
<br>
<input type="file" id="img_file" onChange="img_pathUrl(this);">
Run Code Online (Sandbox Code Playgroud)