繁体   English   中英

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

[英]How to add the nested properties of an object to a FormData object?

我正在使用FormData() (JSON数据和文件FormData()通过提取将数据发送到服务器。 我收到了包含文件的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 Object作为单个键的字符串值发送...

  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"键在服务器上标识您的传入信息,并在到达时进行解析。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM