javascript - 如何将对象的嵌套属性添加到 FormData 对象?

标签 javascript object form-data

我正在使用 FormData() 通过 fetch 将数据发送到服务器,包括 JSON 数据和文件。我收到一个包含文件的 JSON 对象,然后我用 FormData.append() 像这样更新。

var data = {
    title: 'A title',
    img: 'https://fakeimg.pl/500x500/',
    description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
};

let formData = new FormData();
for (var key in data) {
    formData.append(key, data[key]);
}

这有效,但仅在 JSON 对象的第一层。我需要在我的对象中发送数据数组,它可以有文件(我将用 {...} 表示文件):

var data = {
        title: 'A title',
        img: 'https://fakeimg.pl/500x500/',
        description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
        images: [
            { img: 'https://fakeimg.pl/500x500/', imgFile1: {...} },
            { img: 'https://fakeimg.pl/500x500/', imgFile2: {...}  },
            { img: 'https://fakeimg.pl/500x500/', imgFile3: {...}  },
            { img: 'https://fakeimg.pl/500x500/', imgFile4: {...}  },
        ],
    };

我写了这个函数:

function iterateObject(object) {
    for (var key in object) {

        if (Array.isArray(object[key])) {
            object[key].map((item) => {
                iterateObject(item);
            });
        } else if (typeof object[key] === 'object') {
            iterateObject(object[key]);
        } else {
            formData.append(key, object[key]);
        }
    }
}
iterateObject(data);

但在服务器中我最终得到:

{
    title: 'A title',
    img: [
        'https://fakeimg.pl/500x500/',
        'https://fakeimg.pl/500x500/',
        'https://fakeimg.pl/500x500/',
        'https://fakeimg.pl/500x500/',
        'https://fakeimg.pl/500x500/',
    ],
    description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
    images: '[object Object],[object Object],[object Object],[object Object]',
};

有谁知道如何正确更新这个对象,无论嵌套量如何?

最佳答案

实现此目的的一种方法是使用 JSON.stringify 并将 data 对象作为单个键的字符串值发送...

  var data = {
    title: 'A title',
    img: 'https://fakeimg.pl/500x500/',
    description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
    images: [
        { img: 'https://fakeimg.pl/500x500/' },
        { img: 'https://fakeimg.pl/500x500/' },
        { img: 'https://fakeimg.pl/500x500/' },
        { img: 'https://fakeimg.pl/500x500/' }
    ]
};

let formData = new FormData();
formData.append("json_data", "'" + JSON.stringify(data) + "'");

... 然后您可以使用 "json_data" 键在服务器上识别您的传入信息,并在到达时对其进行解析。

关于javascript - 如何将对象的嵌套属性添加到 FormData 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51457134/

相关文章:

javascript - zf2 工具提示中的表单消息 : where does it come from?

javascript - 使用 BACK 按钮恢复到页面的先前状态

javascript - 对象内部的箭头函数

java - 创建同一类的多个对象时出现问题

javascript - JSON、对象和类混淆

php - 如何在 NodeJS 的请求中对表单字段中的数组进行编码?

javascript - Javascript/AJAX 所需的屏幕拦截代码

java - GWT Google Maps V3 覆盖小部件

reactjs - 如何使用 axios 补丁请求发送 FormData?

php - FormData 为空(在 PHP 中)