Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I POST an image to DB via react native with the fetch API?

So I am trying to POST an image to a server via React Native and the fetch API.

      fetch(`${API}/uploadAvatar`, {
        method: "POST",
        headers: {
          Authorization: bearer,
          "X-Requested-With": "XMLHttpRequest",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ file: result.uri }),
      })
        .then((response) => response.json())
        .then((json) => {
          console.log({ json });
          // this console.log outputs:
          // "The format of the file should be jpg, png, jpeg.",
        })
        .catch((err) => {
          console.log({ err });
        });
    }

result returns this:

{
  "cancelled": false,
  "height": 1776,
  "type": "image",
  "uri": "file:///var/mobile/Containers/Data/Application/18F84F29-CB72-4615-A68F-A00422D9B119/Library/Caches/ExponentExperienceData/%2540heythere%252Fkeep-up/ImagePicker/959E8BDE-FCF4-40C6-AF18-8F9EA852760D.jpg",
  "width": 1776,
}

Those are the calls on POSTMAN where you can see they work.

What am I doing wrong?

enter image description here

enter image description here

like image 527
Reacting Avatar asked Oct 29 '25 10:10

Reacting


2 Answers

Your postman shows that you're using form-data to upload the image, but in your code you're simply making a JSON post call without sending any form-data. You need to create a new FormData instance, and append data to it. In your case, you want to send the result.uri with the key file, this can be done using formData.append('file', result.uri). Then you gotta send the formData instance as your body (with method as POST, in your case)

   let formData = new FormData();
   formData.append('file', result.uri);

   fetch("api/SampleData", {
       body: formData,
       method: "post"
     }).then((response) => response.json())
     .then((json) => {
       console.log({
         json
       });
     })
     .catch((err) => {
       console.log({
         err
       });
     });
like image 147
Areeb Khan Avatar answered Oct 31 '25 00:10

Areeb Khan


You can post images to the server with the help of Form Data by creating a JSON object of the file path, file name, and file type and append the object into the Form Data instance with the parameter. The path of the file is Platform-specific therefore you have to add conditions for the path. Please refer to the code snippet.

let Data = new FormData();
Data.append('file',
{ 
uri: Platform.OS === 'android' ? result.uri: result.uri.replace('file://',''),
type: result.type,
name: result.uri.replace(/^.*[\\\/]/, '')
});
fetch("api/SampleData", {
   body: Data,
   method: "post",
   headers: {'Content-Type': 'multipart/form-data'}
 }).then((response) => response.json())
 .then((json) => {
   console.log({
     json
   });
 })
 .catch((err) => {
   console.log({
     err
   });
 });
like image 31
Vishal_VE Avatar answered Oct 31 '25 01:10

Vishal_VE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!