【问题标题】:Multiple image upload with preview and delete option using jQuery使用 jQuery 使用预览和删除选项上传多张图片
【发布时间】:2016-02-24 13:18:23
【问题描述】:

我创建了一个多图像上传器。请查看我的FIDDLE。我目前能够附加图像,预览它们,然后也成功上传它们。也可以删除单个图像。问题是当我删除图像时,目前我的脚本只能删除图像预览,但不能删除要上传的文件。

为了清楚起见,假设我上传了 5 张图片,那么所有 5 张图片都会被预览。但是,如果我使用每个图像顶部的十字删除其中一个图像,那么它只会删除预览。所以,现在如果我点击提交,它会上传所有 5 张图片,但它应该只上传 4 张。

所以,如果有人可以帮助我使用此处的脚本来删除正在上传的文件,而不仅仅是预览。

HTML:

<div id="formdiv">
   <div id="filediv">
     <input type="file" id="file" name="files[]" multiple="multiple" accept="image/*" title="Select Images To Be Uploaded">
        <br>
   </div>
</div>

jQuery

  $('#add_more').click(function() {
          "use strict";
          $(this).before($("<div/>", {
            id: 'filediv'
          }).fadeIn('slow').append(
            $("<input/>", {
              name: 'file[]',
              type: 'file',
              id: 'file',
              multiple: 'multiple',
              accept: 'image/*'
            })
          ));
        });

        $('#upload').click(function(e) {
          "use strict";
          e.preventDefault();

          if (window.filesToUpload.length === 0 || typeof window.filesToUpload === "undefined") {
            alert("No files are selected.");
            return false;
          }

          // Now, upload the files below...
          // https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications#Handling_the_upload_process_for_a_file.2C_asynchronously
        });

        deletePreview = function (ele, i) {
          "use strict";
          try {
            $(ele).parent().remove();
            window.filesToUpload.splice(i, 1);
          } catch (e) {
            console.log(e.message);
          }
        }

        $("#file").on('change', function() {
          "use strict";

          // create an empty array for the files to reside.
          window.filesToUpload = [];

          if (this.files.length >= 1) {
            $("[id^=previewImg]").remove();
            $.each(this.files, function(i, img) {
              var reader = new FileReader(),
                newElement = $("<div id='previewImg" + i + "' class='previewBox'><img /></div>"),
                deleteBtn = $("<span class='delete' onClick='deletePreview(this, " + i + ")'>X</span>").prependTo(newElement),
                preview = newElement.find("img");

              reader.onloadend = function() {
                preview.attr("src", reader.result);
                preview.attr("alt", img.name);
              };

              try {
                window.filesToUpload.push(document.getElementById("file").files[i]);
              } catch (e) {
                console.log(e.message);
              }

              if (img) {
                reader.readAsDataURL(img);
              } else {
                preview.src = "";
              }

              newElement.appendTo("#filediv");
            });
          }
        });

CSS:

#formdiv {
  text-align: center;
}
#file {
  color: green;
  padding: 5px;
  border: 1px dashed #123456;
  background-color: #f9ffe5;
}
#img {
  width: 17px;
  border: none;
  height: 17px;
  margin-left: -20px;
  margin-bottom: 191px;
}
.upload {
  width: 100%;
  height: 30px;
}
.previewBox {
  text-align: center;
  position: relative;
  width: 150px;
  height: 150px;
  margin-right: 10px;
  margin-bottom: 20px;
  float: left;
}
.previewBox img {
  height: 150px;
  width: 150px;
  padding: 5px;
  border: 1px solid rgb(232, 222, 189);
}
.delete {
  color: red;
  font-weight: bold;
  position: absolute;
  top: 0;
  cursor: pointer;
  width: 20px;
  height:  20px;
  border-radius: 50%;
  background: #ccc;
}

【问题讨论】:

  • 在我看来,它们似乎没有从#file 输入中删除——尽管我不确定如何做到这一点。也许这有助于作为一个起点?

标签: javascript jquery


【解决方案1】:

您将无法这样做,因为 FileList 是只读的,这意味着您无法从该对象的选定文件中删除一个文件。你可以阅读它,循环它,但你不能改变选择。

查看此答案以获取更多详细信息:How to remove one specific selected file from input file control

建议的解决方法是使用 FileReader API,但浏览器支持不太理想。

【讨论】:

  • 感谢您的回答。将尝试使用 FileReader APi。但是正如您所说,浏览器支持不好,您能否建议完成这项工作的最佳方法。
  • 多个文件上传总是很麻烦,特别是如果您想要一个好的/出色的用户界面和广泛的浏览器支持。我建议避免重新发明轮子并使用像 blueimp.github.io/jQuery-File-Upload 这样的 JQuery 插件。您可能还对此模块提供的 AJAX 上传功能感兴趣。
  • 谢谢。我首先实现了完全相同的插件。但是看起来有点复杂,有更多的功能和 js。因此,转移到了一个自定义和更简单的解决方案,并最终出现在 FileList 问题中。然后会返回插件。
  • 是的,我在一个项目中使用过它,它肯定有很多您可能不需要的选项和功能。也看看那个:jqueryrain.com/?xFDr2iSl,这里列出了可能感兴趣的其他插件:jqueryrain.com/demo/jquery-file-upload
  • 感谢 jQueryrain 插件。比 blueimp 更易于使用和配置。
【解决方案2】:

在delete中,你只删除了大量的预览节点和元素,你还需要删除输入本身(实际上是上传文件)。

但是,您还必须修复 add 方法,因为您只添加输入,没有包装 div 和 preview 并且具有相同的 id。

【讨论】:

    猜你喜欢
    • 2020-09-27
    • 2021-04-23
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    相关资源
    最近更新 更多