如何在选择图像时显示图像

How to show image while image select

本文关键字:图像 显示图 显示 选择      更新时间:2023-09-26

我正在使用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>

目录

 <form id="imageform" method="post" enctype="multipart/form-data" >
       <input type="file" name="photoimg" id="imgInp" >
       <img id="blah" src="#" alt="your image" />
       <input type="submit" Value="Upload">
       </form>

这段代码完美运行。所以当图像不选择比图像dispaly:none;并且如果图像选择而不是显示图像时,我需要正常。我想用客户端脚本处理这个问题。

修改标记,使图像默认隐藏:

<img id="blah" src="#" alt="your image" style="display:none" />

然后在读取文件后对图像调用 jQuery show 方法,如下所示:

$('#blah').attr('src', e.target.result);
$('#blah').show();

小提琴来了

尝试

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#blah').prop('src', e.target.result);
        }
        reader.readAsDataURL(input.files[0]);
    }
}
jQuery(function () {
    $("#imgInp").change(function () {
        readURL(this);
    });
})

演示:小提琴