如何预览选定的图像在输入类型 = “文件”在弹出使用 jQuery?

在我的代码中,我允许用户上传图像。现在我想显示这个选定的图像作为预览在这个相同的弹出窗口。如何使用 jQuery 实现这一点?

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

HTML 代码:

<input type="file" name="uploadNewImage">
277129 次浏览

You can use ajax upload to preview your selected file.. http://zurb.com/playground/ajax-upload

Demo

HTML:

<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>

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

Reference

If your are using HTML5 then try following code snippet

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

You can use URL.createObjectURL

    function img_pathUrl(input){
$('#img_url')[0].src = (window.URL ? URL : webkitURL).createObjectURL(input.files[0]);
}
#img_url {
background: #ddd;
width:100px;
height: 90px;
display: block;
}
<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);">

Just check my scripts it's working well:

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


// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {


// Only process image files.
if (!f.type.match('image.*')) {
continue;
}


var reader = new FileReader();


// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);


// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}


document.getElementById('files').addEventListener('change', handleFileSelect, false);
#list img{
width: auto;
height: 100px;
margin: 10px ;
}