简体   繁体   中英

POST request with a JSON object that contains a File

I have a JSON object like so:

const people = {
  admin: {
    name: 'john',
    avatar: {
      img: File
    }
  },
  moderator: {
    name: 'jake',
    avatar: {
      img: File
    }
  }
};

The img property is just a File object.


What I want to do

I want to send this data as a POST request to my node server.


What I've tried:

So one approach that seems to work is to create a FormData object and then manually append each property to it like so:

client.js

let formData = new FormData();

formData.append('admin-name', people.admin.name);
formData.append('admin-avatar', people.admin.avatar.img);
formData.append('moderator-name', people.moderator.name);
formData.append('moderator-avatar', people.moderator.avatar.img);

fetch('/submit', { method: 'POST', body: formData })

server.js

import formidable from 'express-formidable';

router.use('/submit', formidable());

router.post('/submit', (req, res) => {
  console.log(req.files); // This contains the Files objects
  console.log(req.fields); // This has the rest of the data
  res.end();
});

Server Output

{ 'admin-avatar': File {}, 'moderator-avatar': File {} }
{ 'admin-name': 'john', 'moderator-name': 'jake' }

The problem with this approach

The main reason I don't like doing it this way is because I have to manually append every single field. I don't think I can do this in a loop because in my data, some of the fields are nested objects. Also, in my server, the data is no longer grouped together like it was in the original object.

Is there any better way to do this? Thanks!

I don't think there is any clean/elegant way of dynamically creating a FormData object. You could solve the repetitiveness by looping over the properties with Object.keys() :

const people = {
  admin: {
    name: 'john',
    avatar: {
      img: {}
    }
  },
  moderator: {
    name: 'jake',
    avatar: {
      img: {}
    }
  }
}

const formData = new FormData()

Object.keys(people)
  .forEach(authority => {
    const { name, avatar: img } = people[authority]
    formData.append(`${authority}-name`, name)
    formData.append(`${authority}-avatar`, img)
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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