如何通过AJAX一次性提交所有上传的文件与逐一提交?

时间:2018-01-20 16:17:30

标签: javascript jquery ajax multipartform-data

下面的代码在drop下提交文件并同时调用,但我尝试将其更改为用户可以在文件后删除文件并立即提交的方式。

我将单独发送文件的函数包装到,但它仍在逐个发送文件。为什么呢?

function handleFileUpload(files, obj) {
  for (var i = 0; i < files.length; i++) {
    var fd = new FormData();
    fd.append('file', files[i]);
    var status = new createStatusbar(obj); //Using this we can set progress.
    status.setFileNameSize(files[i].name, files[i].size);
  }

  var submit = $("#submit-button-id");
  submit.on('click', function(e) {
    e.preventDefault();
    alert("clicked nest!")
    sendFileToServer(fd, status);
  });
}

这是Web API 调用函数:

function sendFileToServer(formData, status) {
  var uploadURL = _config.UploadPrismaTemplates;
  var extraData = {}; //Extra Data.
  var jqXHR = $.ajax({
    xhr: function() {
      var xhrobj = $.ajaxSettings.xhr();
      if (xhrobj.upload) {
        xhrobj.upload.addEventListener('progress', function(event) {
          var percent = 0;
          var position = event.loaded || event.position;
          var total = event.total;
          if (event.lengthComputable) {
            percent = Math.ceil(position / total * 100);
          }
          //Set progress
          status.setProgress(percent);
        }, false);
      }
      return xhrobj;
    },
    url: uploadURL,
    type: "POST",
    contentType: false, //not to set any content header
    processData: false, //not to process data
    cache: false,
    data: formData,
    success: function(data) {
      status.setProgress(100);
      //$("#status1").append("File upload Done<br>");
      alert("set progress success");
    },
    error: function(xhr, status, error) {
      alert(error);
    }
  });

  status.setAbort(jqXHR);

} /*send file to server ends here*/

我在这里修好了!它只会在点击时提交文件。

$(document).ready(function(){
    var drop = $('#drag-and-drop-zone');
    var uploadBtn = $('#submit-button-id');
  drop.on('dragenter', function (e) {
                e.stopPropagation();
                e.preventDefault();
                $(this).css('border', '2px solid #0B85A1');
            });

            drop.on('dragover', function (e) {
                e.stopPropagation();
                e.preventDefault();
            });


            var rowCount = 0;
            function createStatusbar(drop) {
                rowCount++;
                var row = "odd";
                if (rowCount % 2 == 0) row = "even";
                this.statusbar = $("<div class='statusbar " + row + "'></div>");
                this.filename = $("<div class='filename'></div>").appendTo(this.statusbar);
                this.size = $("<div class='filesize'></div>").appendTo(this.statusbar);
                this.progressBar = $("<div class='progressBar'><div></div></div>").appendTo(this.statusbar);
                this.abort = $("<div class='abort'>Abort</div>").appendTo(this.statusbar);
                $('#display-status-id').append(this.statusbar);


                this.setFileNameSize = function (name, size) {
                    var sizeStr = "";
                    var sizeKB = size / 1024;
                    if (parseInt(sizeKB) > 1024) {
                        var sizeMB = sizeKB / 1024;
                        sizeStr = sizeMB.toFixed(2) + " MB";
                    }
                    else {
                        sizeStr = sizeKB.toFixed(2) + " KB";
                    }

                    this.filename.html(name);
                    this.size.html(sizeStr);
                }
                this.setProgress = function (progress) {
                    var progressBarWidth = progress * this.progressBar.width() / 100;
                    this.progressBar.find('div').animate({ width: progressBarWidth }, 10).html(progress + "% ");
                    if (parseInt(progress) >= 100) {
                        this.abort.hide();
                    }
                }
                this.setAbort = function (jqxhr) {
                    var sb = this.statusbar;
                    this.abort.click(function () {
                        jqxhr.abort();
                        sb.hide();
                    });
                }
            }

            /*****************************************/
            drop.on('drop', function (e) {
                $(this).css('border', '2px dotted #0B85A1');
                e.preventDefault();
                var files = e.originalEvent.dataTransfer.files;
                if (!files) return;
                console.log("drop:", drop);

                for (var i = 0; i < files.length; i++) {

                    var status = new createStatusbar(drop);
                    status.setFileNameSize(files[i].name, files[i].size);
                }
                uploadBtn.on('click', function (e) {
                    var fd = new FormData();
                    for (var i = 0; i < files.length; i++)
                    {
                        fd.append(files[i].name, files[i]);

                    }
                    sendFiletoServer(fd);

                });


                function sendFiletoServer(formData) {
                    var uploadURL = "";
                    var extraData = {};
                    var jqXHR = $.ajax({
                        xhr: function () {
                            var xhrobj = $.ajaxSettings.xhr();
                            if (xhrobj.upload) {
                                xhrobj.upload.addEventListener('progress', function (event) {
                                    var percent = 0;
                                    var position = event.loaded || event.position;
                                    var total = event.total;
                                    if (event.lengthComputable) {
                                        percent = Math.ceil(position / total * 100);

1 个答案:

答案 0 :(得分:0)

event.preventDefault() droppable元素事件中调用dragover,使用<button>元素让用户在他们想要上传包含他们拥有的文件的FormData()对象时点击丢弃。

var drop = document.getElementById("drop");
var button = document.getElementById("upload");
var fd = new FormData();
drop.ondragover = function(e) {
  e.preventDefault();
}
drop.ondrop = function(e) {
  e.preventDefault();
  if (e.dataTransfer.types[0] === "Files") {
    var file = e.dataTransfer.files[0];
    fd.append("files[]", file, file.name);
  }
}
button.onclick = function(e) {
  console.log([...fd]);
  // do ajax stuff with `fd` here
  // delete items in `fd` when ajax stuff completes
  for (let [key, prop] of [...fd]) {
    fd.delete(key)
  }
  console.log([...fd]);
}
#drop {
  width: 300px;
  height: 200px;
  border: 2px dotted green;
  text-align: center;
}
<div id="drop">Drop files</div>
<button id="upload">Upload</button>