I'm trying to send to the server an object containing both data and files using fetch.
My object looks like this:
var myData = {
id: 1,
title: 'First project',
description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
img: '/media/images/article-image-3.jpg',
ProjectImages: [
{
id: 1,
img: '/media/images/article-image-1.jpg',
createdAt: '2018-07-21T18:30:46.000Z',
updatedAt: '2018-07-21T18:30:46.000Z',
ProjectId: 1,
imgFile_0: {
lastModified: 1527323312000,
name: 'article-image-1.jpg',
size: 133149,
type: 'image/jpeg',
webkitRelativePath: '',
__proto__: File,
},
},
{
id: 2,
img: '/media/images/article-image-2.jpg',
createdAt: '2018-07-21T18:30:46.000Z',
updatedAt: '2018-07-21T18:30:46.000Z',
ProjectId: 1,
imgFile_1: {
lastModified: 1527323312000,
name: 'article-image-2.jpg',
size: 133149,
type: 'image/jpeg',
webkitRelativePath: '',
__proto__: File,
},
},
],
rating: 2,
ArticleId: 1,
timestamp: '2016-03-13T00:12:09.000Z',
createdAt: '2018-07-21T18:30:46.000Z',
updatedAt: '2018-07-21T18:30:46.000Z',
Tags: [],
imgFile: {
lastModified: 1527323312000,
name: 'article-image-1.jpg',
size: 133149,
type: 'image/jpeg',
webkitRelativePath: '',
__proto__: File,
},
};
As you can see there are some keys with names like imgFiles
, which contains the files. It is not possible to stringify this imgFiles
objects.
I want to send all this data to the server via fetch. I tried transforming it into a FormData
with json-form-data: the files are added to req.files
by https://www.npmjs.com/package/express-fileupload, and req.files
is iterable; but the data, added to req.body
is shaped in this way, and I can't iterate it:
{
'id': '1',
'title': 'First project',
'description':
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. ',
'img': '/media/images/article-image-1.jpg',
'ProjectImages[0][id]': '1',
'ProjectImages[0][img]': '/media/images/article-image-1.jpg',
'ProjectImages[0][createdAt]': '2018-07-21T18:40:52.000Z',
'ProjectImages[0][updatedAt]': '2018-07-21T18:40:52.000Z',
'ProjectImages[0][ProjectId]': '1',
'ProjectImages[1][id]': '2',
'ProjectImages[1][img]': '/media/images/article-image-2.jpg',
'ProjectImages[1][createdAt]': '2018-07-21T18:40:52.000Z',
'ProjectImages[1][updatedAt]': '2018-07-21T18:40:52.000Z',
'ProjectImages[1][ProjectId]': '1',
'rating': '2',
'ArticleId': '1',
'timestamp': '2016-03-13T00:12:09.000Z',
'createdAt': '2018-07-21T18:40:52.000Z',
'updatedAt': '2018-07-21T18:40:52.000Z',
};
So, my questions are:
A. What is the best way to send data along files via fetch?
B. Is possible to transform this structure in a normal object?
EDIT:
It looks like FormData can't handle nested structures. Is a simple and one level depth key: value
data structure. So either I use FormData only to send the files and send the data stringified, or I look for another option.
Any idea will be welcomed!