如何使用 javascript 将多个图像上传到 cloudinary 并将 url 发送到另一个数据库

Posted

技术标签:

【中文标题】如何使用 javascript 将多个图像上传到 cloudinary 并将 url 发送到另一个数据库【英文标题】:How to upload multiple images to cloudinary and send urls to another database using javascript 【发布时间】:2019-12-10 11:09:26 【问题描述】:

这是我第一次发帖,请原谅我的错误。 我正在尝试将多个图像上传到 cloudinary,将 url 保存在一个数组中,并将它们与其余的表单数据一起发送到 mongodb(一个包含多个图像的记录)。 只有在上传了所有图像并将url存储在数组中之后,我才知道如何调用mongodb函数。

我尝试了一个 setTimeout 来等待所有的 url 但没有运气

函数文件输入()

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);

现在第一次上传没有向 mongodb 发送 url,但是第二条记录将前一个列表附加到记录中。 例如,记录 2 将具有记录 1 的图像 url。 这是回购的链接。 https://github.com/Yousuf66/multiple_image_uplaod

【问题讨论】:

【参考方案1】:

您可以在上次上传时将 true 值传递给 addSuspectImage()。然后在将所有 URL 推送到 imgList 之后,在 addSuspectImage() 函数中调用 addSuspect(imgList)

像这样:

 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);
  

【讨论】:

以上是关于如何使用 javascript 将多个图像上传到 cloudinary 并将 url 发送到另一个数据库的主要内容,如果未能解决你的问题,请参考以下文章

如何使用javascript在表单中调整多个图像大小、预览和上传

如何将上传的图像保存到 IndexedDB Javascript

如何使用 Javascript 将多个文件上传到 Azure 存储

如何使用jsp和servlet将多个图像上传到文件夹[重复]

如何将多个图像上传到 Firebase 存储并返回多个下载 URL

如何将多个图像上传到Firebase存储并返回多个downloadURL