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

时间:2018-07-21 14:46:28

标签: javascript object form-data

我正在使用FormData()通过抓取将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]',
};

不管嵌套多少,有谁知道如何正确更新此对象?

1 个答案:

答案 0 :(得分:2)

实现此目标的一种方法是使用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"键在服务器上标识您的传入信息,并在到达时进行解析。

相关问题