Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

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

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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...