Javascript 无后台上传图片预览

Javascript upload image preview without backend

我正在尝试预览照片。每当我单击浏览输入和 select 图像 - 图像出现在 HTML 但当我再次单击浏览和 select 另一张图片时 - 第一张图片被删除并替换为新的 output.innerHTML。有没有办法保留旧的并不断堆叠它们?我是 JS 的超级新手,一段时间以来一直在尝试寻找解决方案,但每个人都建议使用 PHP 并上传到数据库,我可以这样做,但我被要求只使用 vanillaJS 来实现。

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

添加css个样式美化,随意调整