不带后端的JavaScript如何上传图像预览

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (72)

我在试着预览照片。每当我单击“浏览输入”并选择“图像-图像”时,就会出现在HTML中,但是当我再次单击“浏览”并选择另一张图片时,会删除另一张图片,并用新的output.@@有没有办法保持旧的,然后把它们堆起来?

<form id="form" method="post" onchange="loadFile(event)">
    <label for="name">File name:</label>
    <input type="text" id="name" placeholder="Test" value="">

    <label for="description">Description:</label>
    <textarea name="" id="description" cols="30" rows="5" placeholder="Alex" value=""></textarea>

    <label for="file">Upload photo:</label>
    <input type="text" id="browse" placeholder="No file selected" disabled>
    <input type="button" value="Browse" id="loadFilesXml" onclick="document.getElementById('file').click();">
    <input type="file" style="display:none;" id="file" name="file" accept="image/*">

    <div class="flex">
      <input type="submit" name="submit" id="submit" value="Upload">
    </div>
  </form>

  <script>
     let loadFile = function(event) {
     let output = document.getElementById("gallery")
     let src = URL.createObjectURL(event.target.files[0]);
     output.innerHTML = "<div><img src='"+src+"'></div>"
   };
  </script>
提问于
用户回答回答于

你可以这样做:

<form id="form" method="post">
    <label for="name">File name:</label>
    <input type="text" id="name" placeholder="Test" value="">

    <label for="description">Description:</label>
    <textarea name="" id="description" cols="30" rows="5" placeholder="Alex" value=""></textarea>

    <label for="file">Upload photo:</label>
    <input type="text" id="browse" placeholder="No file selected" disabled>
    <input type="button" value="Browse" id="loadFilesXml" onclick="document.getElementById('file').click();">
    <input type="file" style="display:none;" id="file" name="file" accept="image/*">

    <div class="flex">
      <input type="button" name="submit" id="submit" value="Upload" onclick="loadFile(event);">
    </div>
  </form>

  <div id="gallery"></div>

  <script>
     let loadFile = function(event){
         let output = document.getElementById("gallery");
         let file = document.getElementById("file");
         let src = URL.createObjectURL(file.files[0]);
         //output.innerHTML = "<div><img src='"+src+"'></div>";

         var e = document.createElement('div');
         e.innerHTML = "<img src='"+src+"'></div>";
         while(e.firstChild) {
            output.appendChild(e.firstChild);
        }


   };
  </script>

扫码关注云+社区

领取腾讯云代金券