1

I have created a multiple image uploader. Please check my 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. 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.

So, if any one can help me with the script here to delete the files being uploaded and not just the preview.

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;
}
Kiran Dash
  • 4,816
  • 12
  • 53
  • 84
  • It looks to me as though they are not being removed from the `#file` input - though I'm not immediately sure how to do that. Maybe that helps as a starting point though? – Chris O'Kelly Feb 24 '16 at 05:07

2 Answers2

2

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

Community
  • 1
  • 1
Simon Deconde
  • 309
  • 1
  • 4
  • Thanks for your answer. Will give it a try with FileReader APi. But as you said that the browser support is not good, can you please suggest what would be the best way to accomplish the job. – Kiran Dash Feb 24 '16 at 05:21
  • Multiple file uploads are always fiddly to deal with, especially if you want a good/great user interface and a wide browser support. I would suggest to avoid reinventing the wheel and use JQuery plugins like https://blueimp.github.io/jQuery-File-Upload. You might also be interested by the AJAX upload feature that this module offers. – Simon Deconde Feb 24 '16 at 05:32
  • Thanks. I first had implemented the exact same plugin. But looked a bit complex with much more functionalities and js. So, moved to a custom and simpler solution and ended up in FileList issue. Will return to the plugin then. – Kiran Dash Feb 24 '16 at 05:40
  • Yeah, I've used that one for a project, and it definitely has a lot of options and features that you might not need. Have a look at that one too:http://www.jqueryrain.com/?xFDr2iSl and here's a list of other plugins that might be of interest: http://www.jqueryrain.com/demo/jquery-file-upload/ – Simon Deconde Feb 24 '16 at 05:55
  • Thanks for the jQueryrain plugin. Way simpler to use and configure than blueimp. – Kiran Dash Feb 24 '16 at 06:34
0

In delete, you delete only preview node and element from massive, you need to delete input itself as well (that is actually uploading file).

But, you have to fix the add method as well, because you adding only input, without wrapping div and preview and with same id.

faster
  • 151
  • 5