2

I am using the HTML 5 FileReader API to preview images before upload to a server.

As FileReader doesn't have a remove() method, how I can remove an item from the list?

Here is my code

        $("body").on('change', '.files', function() {

          //Get count of selected files
          var countFiles = $(this)[0].files.length;

          var imgPath = $(this)[0].value;
          var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
          var image_holder = $("#image-holder");
          image_holder.empty();

          if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
            if (typeof(FileReader) != "undefined") {

              //loop for each file selected for uploaded.
              for (var i = 0; i < countFiles; i++) {

                var reader = new FileReader();
                reader.onload = function(e) {
                  $("<img />", {
                    "src": e.target.result,
                    "class": "img-thumbnail img-responsive",
                    "width": "100",
                  }).appendTo(image_holder);
                }

                image_holder.show();
                reader.readAsDataURL($(this)[0].files[i]);
              }

            } else {
              alert("This browser does not support FileReader.");
            }
          } else {
            alert("Pls select only images");
          }
        });
<div id="wrapper">
  <div id="image-holder"></div>
</div>

2 Answers 2

3

The Files object is a readonly array-like object, so modifying it is a no-go. One technique seems to be immediately copying its elements into an actual Array and then manipulating the array as needed.

Sign up to request clarification or add additional context in comments.

Comments

-1

Here is an alternative to using FileReader:

// var placed here so that other functions can manipulate
var filesChangeable = []; 
function fileInfo(event){
                       event.preventDefault();

                   // files contains the array of dropped images
                       var files = event.dataTransfer.files;
                       previewFiles(files);

                       function previewFiles(files) {

                       for (var k=0; k<files.length; k++) {

                       var file = files[k];
                       filesChangeable.push(files[k]);    

                       $("#demo").append("<img src='"+URL.createObjectURL(filesChangeable[k])+"' />");

                   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.