How to append multiple file inputs to a FormData object using $.each?

余生颓废 提交于 2019-11-28 09:13:09

There is no good way to see the contents of FormData. A trick would be to send it (POST) and look at the network status.

Example: http://jsfiddle.net/K7aMw/2/

$(document).on("click", "button", function (e) {
    e.preventDefault();
    var inputs = $("#my_form input");
    $.each(inputs, function (obj, v) {
        var file = v.files[0];
        var filename = $(v).attr("data-filename");
        var name = $(v).attr("id");
        myFormData.append(name, file, filename);
    });
    var xhr = new XMLHttpRequest;
    xhr.open('POST', '/echo/html/', true);
    xhr.send(myFormData);
});

Then in the Network tab (F12) you'll see the added files when inspecting the headers.

//your files should be doing something here
var files = yourfileInput[type = file].files

//will upload
var formData = new FormData();
//other info request takes
formData.append("otherInfoKey", $("#otherInfoID").val())
//Now turn to files
for (var i = 0; i < files.length; i++) {
    formData.append(files[i].name, files[i])
}

//Request
var xhr = new XMLHttpRequest();
xhr.open("post", "/upload", true);
xhr.upload.onprogress = function(ev) {
    var percent = 0;
    if (ev.lengthComputable) {
       percent = 100 * ev.loaded / ev.total;
       //$("#yourprogress").width(percent + "%");
       //or something like progress tip
    }
}
xhr.onloadend = function(e) {
    if (!/^2\d*$/.test(this.status)) {
         alert(this.responseText)
    }
}
xhr.onload = function(oEvent) {
    if (xhr.status == 200) {
        //go on
    }
}
xhr.send(formData);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!