如何使用$ .each将多个文件输入附加到FormData对象? [英] How to append multiple file inputs to a FormData object using $.each?

查看:174
本文介绍了如何使用$ .each将多个文件输入附加到FormData对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 type = file 的多个(和动态)输入数。

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

我想用它们创建一个FormData对象。

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:

jsFiddle

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

推荐答案

没有好的方法可以看到FormData的内容。一个技巧是发送它(POST)并查看网络状态。

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.

示例: 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);
});

然后在网络选项卡(F12)中,您会在检查标题时看到添加的文件。

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

这篇关于如何使用$ .each将多个文件输入附加到FormData对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆