0

I am working on an app where I need to send an image blob as FormData alongside some other data sent as Json.

For this I'm making an http post request to the api with the following data:

const blob = new Blob(['some-image], {type: 'image/jpeg'});

const formData = new FormData();

formData.append("file", blob);

const data = {
  name: 'John',
  age: '24',
  uploads: formData
};

For http post request I'm using fetch:

async postData() {
    try {
      const res = await fetch(endpoint, {
          method  : 'POST',
          headers : {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(data),
        });

      return res.status;
    } catch (error) {
      console.log(error)
    }
}

I'm unable to get the file in the backend which just shows an empty object inside uploads['file']. Why is that? Is it not possible to send formData as json with other data?

s.khan
  • 297
  • 1
  • 7
  • 24
  • 1
    Hello, you can't use `JSON` to upload elements to your backend server (don't set the content-type header). Source : https://developer.mozilla.org/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data#the_enctype_attribute https://muffinman.io/blog/uploading-files-using-fetch-multipart-form-data/ https://stackoverflow.com/a/36082038/12554903 – Pioupia Mar 03 '23 at 19:05
  • @Pioupia so I can either send json or form data and not both? – s.khan Mar 03 '23 at 19:07
  • 1
    For me this is not possible. – Pioupia Mar 03 '23 at 19:50

1 Answers1

1

You could just send the FormData as the body.

const formData = new FormData();

formData.append("file", blob);

const data = {
  name: 'John',
  age: '24'
};

// add all key-value pairs of object to the FormData
for (const [key, val] of Object.entries(data))
    formData.append(key, val);

// ...
fetch(endpoint, {
    method  : 'POST',
    body: formData
});

Then you can access the blob as the "file" request parameter and each of the object properties as request parameters also (e.g. "age").

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • Hi, I know about this but I wanted to send json and one of it's value as formdata. I guess it is not possible. – s.khan Mar 04 '23 at 13:04