Skip to content

How to upload multiple images to cloudinary and send urls to another database using javascript

This is my first time posting so please excuse my mistakes. I’m trying to upload multiple images to cloudinary, save the urls in an array and send them along with the rest of the form data to mongodb (one record with multiple images). I cant figure out how to call the mongodb function only after All the images are uploaded and there url’s stored in the array.

i tried a setTimeout to wait for all the urls but no luck

function fileInput(){

var fileInput  = document.getElementById('sus-img');
 var fileList =[];

   for(var i=0;i<fileInput.files.length;i++){
     fileList.push(fileInput.files[i]);
    }
   for(i=0;i<fileList.length;i++){
    //this function uploads the file to cloudinary
     addSuspectImage(fileList[i]);
   }
   //passing the list to the mongodb upload function
   addSuspect(imgList);

}

Right now the first upload sends no url to mongodb, however the second record appends the previous list to the record. for eg record 2 would have the image urls of record 1. here is a link to the repo. https://github.com/Yousuf66/multiple_image_uplaod

Answer

You can pass a true value to addSuspectImage() on the last upload. Then call addSuspect(imgList) within the addSuspectImage() function, after pushing all URL’s to imgList.

Like this:

 function fileInput(){

    var fileInput  = document.getElementById('sus-img');
     var fileList =[];
     // let count = 0;
     var isLastUpload=false;
       for(var i=0;i<fileInput.files.length;i++){
         fileList.push(fileInput.files[i]);
        }
       for(i=0;i<fileList.length;i++){
         console.log(fileList[i]);
          if(i==fileInput.filesList.length-1){
              isLastUpload=true;
            } 
         addSuspectImage(fileList[i], isLastUpload);
       }
   }

  function addSuspectImage(file,isLastUpload){

   {console.log(file);

    var url = `https://api.cloudinary.com/v1_1/${cloudName}/upload`;
    var xhr = new XMLHttpRequest();
    var fd = new FormData();

    xhr.open('POST', url, true);
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');


    xhr.onreadystatechange = function(e) {
      if (xhr.readyState == 4 && xhr.status == 200) {
        // File uploaded successfully

        // var response = JSON.parse(xhr.responseText);
      var response = JSON.parse(xhr.responseText);
      console.log(response);


      console.log("uploaded");
        // https://res.cloudinary.com/cloudName/image/upload/v1483481128/public_id.jpg


      var url = response.secure_url;
      console.log(url);
      imgList.push(url);

      }

     if(isLastUpload){
        addSuspect(imgList);
       }
    };
       fd.append('upload_preset', unsignedUploadPreset);
       fd.append('tags', 'browser_upload'); // Optional - add tag for image admin in Cloudinary
    fd.append('file', file);
    xhr.send(fd);
  }
}