Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

javascript - Choose multiple images and upload with preview

I need to add multiple images for upload. Below is my form. In the form, if you kindly check run code snippet`, when I upload image one by one, images with preview shown but no of images are not increased (here shows 2 files though total 4 images are present). but when I select multiple images at a time, then no of selected images shows.

In the attached image, it shows 4 images but no of count shows only 2 files. This is the problem.

I want to know, is it possible to increase no of files, when I choose images one by one i.e. with single click and select one image?

$(document).ready(function() {
  if (window.File && window.FileList && window.FileReader) {
    $("#files").on("change", function(e) {
      var files = e.target.files,
        filesLength = files.length;
      for (var i = 0; i < filesLength; i++) {
        var f = files[i]
        var fileReader = new FileReader();
        fileReader.onload = (function(e) {
          var file = e.target;
          $("<span class="pip">" +
            "<img class="imageThumb" src="" + e.target.result + "" title="" + file.name + ""/>" +
            "<br/><span class="remove">Remove image</span>" +
            "</span>").insertAfter("#files");
          $(".remove").click(function(){
            $(this).parent(".pip").remove();
          });
        });
        fileReader.readAsDataURL(f);
      }
    });
  } else {
    alert("Your browser doesn't support to File API")
  }
});
input[type="file"] {display: block;}
.imageThumb {max-height: 75px; border: 2px solid; padding: 1px; cursor: pointer;}
.pip {display: inline-block; margin: 10px 10px 0 0;}
.remove { display: block;background: #444;border: 1px solid black;color: white;text-align: center;cursor: pointer;}
.remove:hover {background: white;color: black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <h3>Upload your images</h3>
  <input type="file" id="files" name="files[]" multiple /></br>
  <input type="submit" name="submit" value="Submit">
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is because you are relying on the browser's default <input>'s UI, which will only show its current content.

So if you want to upload all the Files that got selected, create an Array where you'll store all your Files, at every change.

Then to send it to your server, you will block the default behavior of your <form> by blocking its submit event, and sending a FormData filled with your files through XHR.

$(document).ready(function() {
  // First define the Array where we will store all our files
  var myFiles = [];
  // now, every time the user selects new Files,
  $("#files").on("change", function(e) {
    var files = e.target.files, file;
    // iterate through all the given files
    for (var i = 0; i < files.length; i++) {
      file = files[i];
      myFiles.push(file); // store it in our array
      $('<span class="pip">' +
        '<img class="imageThumb" ' +
        // no need for a FileReader here,
        //  a blobURI is better (sync & uses less memory)
        'src="' + URL.createObjectURL(file) + '" ' +
        'title="' + file.name + '"/>' +
        '<br/>' +
        '<span class="remove">Remove image</span>' +
        '</span>')
      .insertAfter("#files")
      // add the event listener only on the new .remove
      .find(".remove").click(removeFile.bind(null, file));
    }
    updateCounters();
  });

  // now override the default form submission
  $('form').on('submit', upload);

  // removes both the preview elements from doc and the file from our array
  function removeFile(file, evt) {
    $(evt.target).parent(".pip").remove();
    myFiles.splice(myFiles.indexOf(file), 1);
    updateCounters();
  }
  // ...
  function updateCounters() {
    $('#counter').text(myFiles.length + ' files selected');
  }
  // from submission overriding function
  function upload(evt) {
    evt.preventDefault(); // first block the default event
    var fd = new FormData(); // create a new FormData
    for (var i = 0; i < myFiles.length; i++) {
      fd.append('files[]', myFiles[i]); // append all our files to it
    }
    // Post the formdata through XHR
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'YOUR_FORM_ACTION_URL');
    // if you wanted to do something after the files are submitted
    // xhr.onload = callback;
    xhr.send(fd);
  }
});
input[type="file"] {
  display: block;
}

.imageThumb {
  max-height: 75px;
  border: 2px solid;
  padding: 1px;
  cursor: pointer;
}

.pip {
  display: inline-block;
  margin: 10px 10px 0 0;
}

.remove {
  display: block;
  background: #444;
  border: 1px solid black;
  color: white;
  text-align: center;
  cursor: pointer;
}

.remove:hover {
  background: white;
  color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <h3>Upload your images</h3>
  <span id="counter">0 files selected</span>
  <input type="file" id="files" name="files[]" multiple /><br>
  <input type="submit" name="submit" value="Submit">
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...