簡體   English   中英

使用 AJAX 在序列/隊列中上傳多個文件

[英]Multiple File Upload using AJAX in sequence/queue

我是 Javascript 和 jQuery 的新手。 在表單中上傳N個文件時,只上傳最后一個文件N次,

我想通過 AJAX 請求一次(異步)上傳每個文件。

下面是我的實現:

 $("#file-input").on("input", function() { var formdata = new FormData(document.getElementById("file-catcher")); $.each($("#file-input")[0].files, function (key, file){ formdata.append(key, file); // This is to Inspecting each file for(var pair of formdata.entries()) { console.log(pair[0]+ ': '+ pair[1]); } // Sending AJAX $.ajax({ type: "POST", data: formdata, url: "/url/to/upload", datatype: 'JSON', contentType: false, cache: false, processData: false, success:function(data){ console.log(data); // Inspecting Response }, error: function (error) { console.log(error); // Inspecting Error if occured } }); }); });
 <form method="POST" id="file-catcher" action="/url/to/upload" enctype="multipart/form-data"> <input type="text" name="fileCode" value="10"> <input type="file" id="file-input" name="file-input" multiple> </form>

我要感謝Chris G指導我遍歷每個文件以創建隊列並按順序發送文件。

const inputFile = document.getElementById('file-input');

// Iterating through each file and sending AJAX request
for (const file of inputFile.files){

  var formdata = new FormData(document.getElementById("file-catcher"));

  formdata.append("file-input", file);

  $.ajax({
        type: "POST",
        data: formdata,
        url: "/url/to/upload",
        datatype: 'JSON',
        contentType: false,
        cache: false,
        processData: false,
        success:function(data){
          console.log(data);
        },
        error: function (error) {
          console.log(error);
        }
  });

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM