首页 > 解决方案 > 在使用javascript在html中上传图像之前显示缩略图不起作用

问题描述

我有一个用 html 设计的表单,该表单有 2 张图片上传,我试图在用户提交表单之前向他显示缩略图,我有以下代码:

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

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

    reader.readAsDataURL(input.files[0]);
  }
<div class="col-sm-4">
  <img id="imaged" style="width:150px; height: 150px; border-radius:50%;" src="" alt="image">
  <input onchange="readURL(this);" type="file" name="" class="form-control" style="margin-top:2%;">
</div>
<div class="col-sm-4">
  <img style="width:150px; height: 150px; border-radius:50%;" src="" alt="image">
  <input id="imageds" type="file" onchange="readURL(this);" name="" class="form-control" style="margin-top:2%;">
</div>

但是,这不会将图像显示为缩略图,而只是在“选择文件”按钮附近显示图像名称。谁能告诉我这里可能出了什么问题,在此先感谢

标签: javascripthtmlformsimagemultipartform-data

解决方案


  1. 您忘记在 readURL() 中关闭大括号
  2. 您将 id 图像放错位置以输入标签而不是图像标签

所以最终的代码就像

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

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

    reader.readAsDataURL(input.files[0]);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-4">
    <img id="imaged" style="width:150px; height: 150px; border-radius:50%;" src="" alt="image">
    <input onchange="readURL(this);" type="file" name="" class="form-control" style="margin-top:2%;">
</div>
  <div class="col-sm-4">
    <img id="imageds" style="width:150px; height: 150px; border-radius:50%;" src="" alt="image">
  <input type="file" onchange="readURL(this);" name="" class="form-control" style="margin-top:2%;">
</div>


推荐阅读