简体   繁体   English

使用jQuery使用预览和删除选项上传多张图片

[英]Multiple image upload with preview and delete option using jQuery

I have created a multiple image uploader. 我创建了一个多图像上传器。 Please check my FIDDLE . 请检查我的FIDDLE I am currently able to attach the image, preview them and then also successfully upload them. 我目前可以附加图像,预览图像,然后也可以成功上传。 And also the individual images can be deleted. 而且单个图像也可以删除。 The problem is when I delete the images, currently my script is only able to delete the image preview but not deleting the files to be uploaded. 问题是当我删除图像时,当前脚本只能删除图像预览,而不能删除要上传的文件。

To be clear, say if I uploaded 5 images, then all 5 images are previewed. 明确地说,假设我上传了5张图片,那么所有5张图片都会被预览。 But then If I delete one of the image using the cross that I have on top of every image then it just deletes the preview. 但是,如果我使用每张图片上方的叉号删除其中一张图片,则它只会删除预览。 So, now if I click on submit then it uploads all 5 images but it should upload only 4. 因此,现在,如果我单击“提交”,则它将上传所有5张图像,但应该仅上传4张图像。

So, if any one can help me with the script here to delete the files being uploaded and not just the preview. 因此,如果有人可以帮助我使用此处的脚本删除正在上传的文件,而不仅仅是预览。

HTML: 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 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: 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;
}

You won't be able to do it this way as a FileList is read-only, meaning that you can't remove one file out of the selected files from that object. 由于FileList是只读的,因此您将无法通过这种方式进行操作,这意味着您无法从该对象的所选文件中删除一个文件。 You can read it, loop over it, but you can't change the selection. 您可以阅读,循环浏览,但是不能更改选择。

Have a look at this answer for more detailed info: How to remove one specific selected file from input file control 请查看此答案以获取更多详细信息: 如何从输入文件控件中删除一个特定的选定文件

The suggested workaround is to use the FileReader API, but the browser support is less than ideal. 建议的解决方法是使用FileReader API,但浏览器支持不理想。

In delete, you delete only preview node and element from massive, you need to delete input itself as well (that is actually uploading file). 在delete中,您只从大量节点中删除预览节点和元素,还需要删除输入本身(实际上是在上传文件)。

But, you have to fix the add method as well, because you adding only input, without wrapping div and preview and with same id. 但是,您还必须修复add方法,因为您只添加了输入,而没有包装div和Preview并且具有相同的ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM