Question

I have a multiple (and dynamic) number of inputs of type=file.

I want to create a FormData object out of them.

I need to manually append them to the object as I need access to their filenames for inserting into a database and therefore need to specify a filename is this format:

myFormData.append(name,file,filename);

HTML

<form id="my_form" enctype="multipart/form-data">
    <input type="file" name="undefined" id="file_1" data-filename="image.jpg">
    <input type="file" name="undefined" id="file_2" data-filename="image2.jpg">
    <button>click</button>
</form>

jQuery

var myFormData = new FormData();

$(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);
    });

    //alert(JSON.stringify(myFormData));
    console.log(myFormData);
});  

I don't think the object is being constructed properly and I haven't been able to correctly view the contents of the object to confirm this.

This is what I get in the console:

enter image description here

jsFiddle

http://jsfiddle.net/rwone/K7aMw/

Was it helpful?

Solution

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.

OTHER TIPS

//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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top