使用 javascript 在 html 中上传图片前显示缩略图无效

showing thumbnail before image upload in html using javascript not working

我有一个在 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>

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

  1. 您忘记在 readURL() 中关闭大括号
  2. 你把 id imageds 放错了输入标签而不是图像标签

所以最终代码会像

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>