简体   繁体   中英

Javascript XMLHttpRequest FormData sending doesn't work

I want to upload some files to my server with a drag'n'drop angularjs directive. I've hardcoded for hours but I haven't still found the error. I have that angularjs code:

var fd = new FormData();

for(x = 0; x < files.length; x++)
    fd.append("file[]", files[x]);
    fd.append('type', 'upload');
    xhr = new XMLHttpRequest();
xhr.open("post", "/../RESOURCES/API/explorer.php", true);
    xhr.upload.addEventListener("progress", function(e) {
    var pc = parseInt(100 - (e.loaded / e.total * 100));
    console.log(pc);
}, false);
    xhr.onload = function() {
    console.log(xhr.responseText);
};
xhr.send(fd);

But my APIs returns empty $_POST and $_FILES. Thanks!

With Angular JS, I've achieved file upload with the following code:

angular.module('frApp')
  .service('fileUpload', ['$http',function ($http) {

    this.uploadFileToUrl = function(file, uploadUrl, success, error){
      var fd = new FormData();
      fd.append('file', file);
      $http.post(uploadUrl, fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
      }).success(success)
        .error(error);
    };
  }]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM