Home > Software design >  Does there exist a 'good-practice' way to send files without relying on FormData?
Does there exist a 'good-practice' way to send files without relying on FormData?

Time:03-17

I'm currently working on an app with a React Native front-end and Node.js/Express backend. I am perfectly able to upload files using FormData with Content-Type multipart/form-data. The problem I have is that when using FormData, any other data that you wish to send in the body of the request is necessarily converted to a string. This isn't the case when one simply sends a JS object as the body of the request (as long you parse it on the backend of course). I wish to know if there is a good-practice way to send a file/files alongside JSON in a request, without losing the typings of said JSON?

Thanks

CodePudding user response:

Add your data as JSON in a field of the FormData:

const data = {
  foo: ["bar", 1]
};
const file = new File(["some content"], "myfile.txt");
const formdata = new FormData();
formdata.append("file", file);
// Send as JSON
formdata.append("data", JSON.stringify(data));

const req = new Request("./", { method: "POST", body: formdata });

// simulate server side getting the response
req.formData().then( (fd) => {
  const received_file = fd.get("file");
  // parse JSON
  const received_data = JSON.parse(fd.get("data"));
  console.log({ received_file, received_data });
});

CodePudding user response:

When you insist on sending the image along with other data inside the JSON, then AFAIK your only option is to convert the image to some data type which can be transmitted via JSON.

The most obvious choice would be a string, and what is usually used here is the base64 encoding. It is, however, not very efficient and can cause lag.

What is sometimes done to stay within the JSON domain but still being able to upload images is to create two endpoints. One for the JSON data. One for the image upload in a binary format.

  • Related