Search code examples
javascripthtmlfile-uploadimage-uploading

Multiple Image Uploader with Preview


I've created an Image Uploader but it's not working properly. I'm not able to understand where am I going wrong. The JSFIDDLE of my image uploader is given below:

JSFIDDLE

The problem I am facing is when I click on choose files and select more than one files and open it, I wanted it to show the preview of all the images which I selected and it works properly but when I click on delete button it only deletes the preview that means if I submit the files even those files which I have deleted would be uploaded. On another hand I have to click Add more images button to create one more uploader same as above but when I add multiple images it does not show any preview so I cant even select or delete the images which I've selected by mistake. Can anyone find where am I going wrong. I need that add more images button too so that if we forget adding some images or the images are in different directory we can call one more input type files and that should function the same as previous.


Solution

  • So, you were doing some odd things (like using a global variable with an integer assigned to it that I'm assuming you were using to keep track of your objects).

    I've cleaned up what you had going on, and removed some redundant functions. Essentially, you needed to better utilize the JavaScript FileReader() function. You'll need to take a closer look at your buttons; as I didn't fix them for you. ;)

    What you needed to do was iterate through your this.files array, and display the results using the FileReader() function. Code below.

        $('#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
        });
    
        function deletePreview(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='abcd'><img /></div>"),
                deleteBtn = $("<span class='delete' onClick='deletePreview(this, " + i + ")'>delete</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");
            });
          }
        });
    #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;
    }
    .abcd {
      text-align: center;
      position: relative;
    }
    .abcd img {
      height: 200px;
      width: 200px;
      padding: 5px;
      border: 1px solid rgb(232, 222, 189);
    }
    .delete {
      color: red;
      font-weight: bold;
      position: absolute;
      top: 0;
      cursor: pointer
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <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>
      <input type="button" id="add_more" class="upload" value="Add More Images" />
      <input type="submit" name="submit" value="Add Product" class="upload" id="upload" title="Add Product To The Inventory">
    </div>