Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image upload in React Native (Expo), using fetch results in 400 error

I have been struggling with image upload for days. I’m using formdata like this:

let formData = new FormData();
formData.append('file', {
  uri: uri,
  name: `name`,
  type: `image/jpeg`,
});

uri on iOS is something like asset-library://asset/path on Android it is like content://media/external/images/media/25377.

let options = {
  method: 'POST',
  body: formData,
  headers: {
    Accept: 'application/json',
    'Authorization': 'Bearer ' + token,
  },
};
let response = await fetch("https://myserverurl", options)

I tried every trick reading the image as blob, removing content-type, other libraries like axios, etc… No matter what I always get back a 400 bad file format error.

Is there something I’m missing with formdata? (On the backend we use ASP.NET)

like image 345
marchello Avatar asked Dec 21 '25 09:12

marchello


1 Answers

We have had a similar issue and were able to solve the issue the following way. We are using a NodeJS backend (with multer) to handle the file uploads.

Expo - Mobile App Code

  // extract the filetype
  let fileType = uri.substring(uri.lastIndexOf(".") + 1);

  let formData = new FormData();

  formData.append("photo", {
    uri,
    name: `photo.${fileType}`,
    type: `image/${fileType}`
  });

  let options = {
    method: "POST",
    body: formData,
    headers: {
      Accept: "application/json",
      "Content-Type": "multipart/form-data"
    }
  };

We are executing the request with fetch(apiUrl, options).

The uri is the local file path (full URI e.g., file:///...) of the photo in our case and apiUrl is the endpoint of the server-side.

I think the issue might be with the type and format of uri in formdata. Have you tried to use the uri returned by the image picker?

like image 135
meck93 Avatar answered Dec 23 '25 23:12

meck93



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!