-1

I was working on building rest API, Where I want to upload multiple images with one post request.

So here. I am trying to make an array of base64 string of selected images. That array is JSON.stringify(images_to_upload) to convert to string. and send that string as JSON post. and on server side use json_decode() to decode the string array and save the images.

Is my approach correct? i am not able to execute JSON.stringify(images_to_upload) as this returns nothing.

is there any better way to handle this?

JAVASCRIPT

  $("#UploadImage").click(function(){
    var filesSelected = document.getElementById("filesToUpload").files;
    var images_to_upload = new Array();
    //Loop through each image
    for(var i=0;i<filesSelected.length;i++)
    {
      var fileToLoad = filesSelected[i];
      var fileReader = new FileReader();
      fileReader.onload = function(fileLoadedEvent){
        var img_string = fileLoadedEvent.target.result;
        //push base64 string in arrray
        images_to_upload.push(img_string);
      };
      fileReader.readAsDataURL(fileToLoad);
     }

    console.log(JSON.stringify(images_to_upload));  //this doesnt work
    data = {
      "images_data":JSON.stringify(images_to_upload) ,
      };
    url = "http://app.com/api/customer/uploadmultipleimg";
    $.ajax({
      type: "POST",
      url: url,
      data:data,
      success: function(result){
        console.log(result);
      },
      failure: function(errMsg) {
         console.log(errMsg);
      }
      });
  });

HTML

<input type="file" name="filesToUpload" id="filesToUpload" multiple="" accept="image/x-png,image/jpeg">
<input type="submit" value="UploadImage" id="UploadImage" name="submit">
Pramit Sawant
  • 682
  • 1
  • 9
  • 17

1 Answers1

1

I think you might be hitting a race condition. I've updated the code to only make the call to the API when the final image has been processed by the FileReader. This is reliably showing the array and its contents in the console in my test version.

$(document).ready(attach_upload_button_click_handler);

function attach_upload_button_click_handler() {
    $("#UploadImage").click(upload_images);
}

function upload_images() {
    var selected_files = document.getElementById("filesToUpload").files;
    var images_to_upload = new Array();

    for (let i = 0; i < selected_files.length; i++) {

        var fileReader = new FileReader();
        fileReader.onload = function (event) {
            images_to_upload.push(event.target.result);

            if (i == selected_files.length - 1) {
                post_data_to_api(images_to_upload);
            }
        };

        fileReader.readAsDataURL(selected_files[i]);
    }
}

function post_data_to_api(images_to_upload) {
    console.log(JSON.stringify(images_to_upload));

    // CALL API
}
Pseudonymous
  • 839
  • 5
  • 13