Javascript异步多文件上传XMLHttpRequest处理程序错误

时间:2015-09-02 16:45:27

标签: javascript jquery ajax asynchronous

我有一个文件上传,旨在处理多个图像。每个图像都有一个基于ID的基于图像上传的顺序 - 我想要发送的帖子和帖子请求。因此,我遍历fileSelect.files并使用XMLHttpRequest上传图片。

如果我使用xhr.open('POST', ajaxURL, false);asynchronous设置为false)则没有问题;我的xhr.onload = function () {...};正确返回每个上传图片的服务器响应。

但是,如果我尝试使用xhr.open('POST', ajaxURL, true);(将asynchronous设置为true),则处理程序会混淆并仅输出有关上次上传文件的信息。

我认为这可能是因为为循环的每次迭代调用一个新的xhr.open('POST', ...);。是否有一种很好的方法可以使处理程序与异步请求一起工作,或者以我只需要发出一个请求的方式附加表单数据?这是一个问题,因为我想确保每次上传都已成功完成。

我的工作javascript是

// image upload handler
$(fileSelect).change(function(){

   // get the information we need to upload an image
   var ajaxURL = $("#action").val();
   var CSRFToken = document.getElementsByName('csrfmiddlewaretoken')[0].value;
   var house_id = $("#house_id").val();
   console.info("Uploading files to " + ajaxURL + " with using house_id=" + house_id + " and a csrf token value of " + CSRFToken);

   // make an AJAX call to upload the image
   uploadImage(this, ajaxURL, CSRFToken, house_id);
});

/**
 * Upload each image file in the given fileSelect object
 * via an AJAX request to the specified URL using the provided
 * CSRF token. A house_id parameter must be provided for the database
 * to organize image uploads by house.
 */
var uploadImage = function(fileSelect, ajaxURL, CSRFToken, house_id) {
   // get the selected files from the input
   var files = fileSelect.files;

   // create the object resposible for handling the ajax request
   var xhr = new XMLHttpRequest();
   xhr.onload = function () {
      if (xhr.status === 200) {
     alert(xhr.statusText + ": " + xhr.responseText)
      } else {
     alert("Oops! The file upload failed. Please try again.");
      }
   };

   // loop through each of the selected files
   for (var i = 0; i < files.length; i++) {
      var file = files[i];

      // check the file type
      if (!file.type.match('image.*')) {
     // if it's not an image -> alert user & dont upload
     alert(file.name + " could not be added because it is of the wrong filetype.");
     continue;
      }

      console.log("Uploading " + file.name + " . . .");

      // create a new FormData object for our images
      var formData = new FormData();

      // append the current image and related values to our form data
      formData.append('file', file);
      formData.append('csrfmiddlewaretoken', CSRFToken);
      formData.append('house_id', house_id);
      formData.append('image_id', i);

      // make the request and set a handler
      xhr.open('POST', ajaxURL, false);
      xhr.send(formData);
   }

};

0 个答案:

没有答案