我正在使用 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/