react-native: Network Error when send file with formData(axios or fetch) on Android. Works fine on IOS.

Description

When I try to send some post request sending a file with formData I receive a Network Error. Most of the time the request works fine, but sometimes I receive this error. The problem occurs when use Android, works fine with IOS.

Recently I updated my application to react-native 0.74.1(latest), before the version was 0.64.4. In older version all works fine.

Current versions:

  • React native: 0.74.1
  • Node: >= 18
  • React: 18.2.0
image

Steps to reproduce

Only try to submit some files using formData

React Native Version

0.74.1

Affected Platforms

Runtime - Android

Output of npx react-native info

System:
  OS: macOS 14.4
  CPU: (8) x64 Intel(R) Core(TM) i5-8257U CPU @ 1.40GHz
  Memory: 29.93 MB / 8.00 GB
  Shell:
    version: "5.9"
    path: /bin/zsh
Binaries:
  Node:
    version: 18.19.0
    path: /usr/local/bin/node
  Yarn:
    version: 1.22.22
    path: /usr/local/bin/yarn
  npm:
    version: 8.19.4
    path: /usr/local/bin/npm
  Watchman:
    version: 2024.05.06.00
    path: /usr/local/bin/watchman
Managers:
  CocoaPods:
    version: 1.15.2
    path: /usr/local/bin/pod
SDKs:
  iOS SDK:
    Platforms:
      - DriverKit 23.4
      - iOS 17.4
      - macOS 14.4
      - tvOS 17.4
      - visionOS 1.1
      - watchOS 10.4
  Android SDK:
    API Levels:
      - "29"
      - "30"
      - "31"
      - "32"
      - "33"
      - "34"
    Build Tools:
      - 29.0.2
      - 30.0.2
      - 30.0.3
      - 31.0.0
      - 33.0.0
      - 33.0.1
      - 34.0.0
    System Images:
      - android-29 | Google APIs Intel x86 Atom
      - android-29 | Google Play Intel x86 Atom
      - android-30 | Intel x86_64 Atom
      - android-34 | Google APIs Intel x86_64 Atom
      - android-34 | Google Play Intel x86_64 Atom
      - android-VanillaIceCream | Google APIs Intel x86_64 Atom
    Android NDK: Not Found
IDEs:
  Android Studio: 2023.2 AI-232.10300.40.2321.11567975
  Xcode:
    version: 15.3/15E204a
    path: /usr/bin/xcodebuild
Languages:
  Java:
    version: 17.0.10
    path: /usr/bin/javac
  Ruby:
    version: 2.6.10
    path: /usr/bin/ruby
npmPackages:
  "@react-native-community/cli": Not Found
  react:
    installed: 18.2.0
    wanted: 18.2.0
  react-native:
    installed: 0.74.1
    wanted: ^0.74.1
  react-native-macos: Not Found
npmGlobalPackages:
  "*react-native*": Not Found
Android:
  hermesEnabled: true
  newArchEnabled: false
iOS:
  hermesEnabled: true
  newArchEnabled: false

Stacktrace or Logs

No have logs to show

Reproducer

https://github.com

Screenshots and Videos

No response

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 7
  • Comments: 46 (1 by maintainers)

Most upvoted comments

To fix the “Network Error when sending file with FormData (axios or fetch) on Android” issue — especially when it works fine on iOS — the problem usually lies in how the file is formatted and how headers are set.

** working solution for Android**, especially with axios, rewriting your code properly:

✅ Corrected Code (No file key inside the object)

import mime from 'mime';

const formData = new FormData();

formData.append('image', {
  uri: file.uri,
  type: mime.getType(file.uri),
  name: fileName,
});

⚠️ Note:

  • Use mime for type of the files

const type = mime.getType('my-image.png'); 
console.log(type); // 'image/png

⚠️ Do Not:

  • Add a file property inside the object (file: file) — Android throws network errors.
  • Set Content-Type manually to multipart/form-data with axios — let it set the boundary itself.

✅ Axios Call (without setting Content-Type manually):

axios.post(uploadUrl, formData, {
  headers: {
    Accept: 'application/json',
    // Don't set 'Content-Type': multipart/form-data manually
  },
})
.then(response => console.log(response.data))
.catch(error => console.log(error));

💡 Notes:

  • Ensure uri is in correct format: file:// on Android.
  • If you’re using Expo, and the URI is like content://..., convert it to file://... using expo-file-system or react-native-image-picker.

This is my code that works, thanks @ganeshmohane

const getExtension = (fileName) => {
  const lastDotIndex = fileName.lastIndexOf('.');
  if (lastDotIndex === -1 || lastDotIndex === 0) {
    return '';
  }

  switch (fileName.substring(lastDotIndex + 1)) {
    case 'pdf':
      return 'application/pdf';
    case 'jpg':
      return 'image/jpeg'; // there is no mime type 'image/jpg'
    case 'jpeg':
      return 'image/jpeg';
    case 'png':
      return 'image/png';
  }
}
const upload = async (file, fileName) => {
  const url = Endpoints.fileStorage.upload;
  const formData = new FormData();


  formData.append(
    "image",
    {
      uri: file.uri,
      type: getExtension(fileName), 
      name: fileName,
      file: file,
    }
  );

  FileSystem.getInfoAsync(file.uri)
    .then(stats => {
      if (stats.exists) {
        console.log('File exists: ', stats );
      }
      else {
        console.log('File not exist');
      }
    }).catch(error => {
      console.log(error);
    });
  
  const response = await httpService.post(url, formData, true, false, {
    headers: {
      'Content-Type': 'multipart/form-data',
      'Accept': 'application/json'
    },
  }).catch(error => {
    if (error.response && error.response.status === 400) {
      console.log("msg: ", error.message);
    }
  });

  return response;
};

updating from 0.73 to 0.77.1 broke something and I am getting Network Error (android ONLY),

however after adding:

Content-Type’: ‘multipart/form-data’

the Network Error disappears.

async function postFormdata({ fields, contentType, assetUri, uploadUrl }) {
  const data = new FormData();

  for (const field of fields) {
    data.append(field.key, field.value);
  }

  // data.append('file', { uri: assetUri, type: contentType,  });
  data.append('file', { uri: assetUri, type: contentType, name: 'dummy.jpg' });

  const CancelToken = axios.CancelToken;
  const source = CancelToken.source();

  const config = {
    cancelToken: source.token,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  };

  setTimeout(() => source.cancel(), 1000 * 60 * 2); /* in 2 mins, cancel the request */

  try {
    await axios.post(uploadUrl, data, config);
  } catch (e) {

same issue in android

The problem is buried down into com.facebook.react.modules.network.NetworkingModule.constructMultipartBody(...) method. It expects to find Content-type header in the FormData part, containing the URI to the file. Something like this:

const part = {
    headers: [ ['content-type', 'image/png'] ],
    uri: 'file:///...',
    name: fileName,
    mimeType: 'image/png'
}

If there is no Content-type header, even though mimeType for the part is provided, the method returns null (line 725 in version 0.76.5) which causes the entire request to go silently into the trash, causing this nice and informative “Network error”

Even better - if you explicitly specify headers property in your FormData part it will not help you, because somewhere in the transit between the layers, the headers are overwritten mercilessly with content-disposition header. Thus, no matter what you provide in your request, only the content-disposition header reaches the NetworkingModule.

I was able to workaround the problem by registering custom RequestBodyHandler with the NetworkingModule and re-routing the processing of “form-data” payload to it, but it was ugly.

@lokeshchoudharyprogrammer, correct, a lot of people set the type wrong, which is the cause of this network error

Same for me, but I saw another post like this, and I tried putting a default value like this for teh type and name seems to solve the problem for me.

        thumbFormData.append('images[]', {
           uri: path,
           type: data.mime || 'image/jpeg',
           name: fileName || 'thumbnail.jpg',
         });

same issue, any found solution?

Having the same problem, only on Android as well. Using Axios worked

Here not work using axios or fetch. =(

Hi @bestchenyan,

You can find example workaround implementation here: https://github.com/simeon-kirov/expo-debug/tree/main. I tried to describe what’s done in the README and inline JavaDoc.

However, you’re saying in your case it always returns HTTP error 403. This is different from what I observe. In my case I’m getting just “Network error” message without any HTTP code. Probably your problem is related to self-signed/untrusted SSL certificates on the server. Make sure that you’ve registerd your server certificates as trusted. Check this documentation: https://developer.android.com/privacy-and-security/security-config. Also, you can see the configuration in my project:

  • android/app/src/debug/AndroidManifest.xml
  • android/app/src/debug/res/xml/network_security_config.xml
  • android/app/src/debug/res/raw/trusted_certificates

Hi Everyone, Mine got fixed after some troubleshooting…All I did was that I removed Content-Type part from headers and It worked

not work here =(

I had the same problem after upgrade React Native to 0.72.17. And in my case renamed from Content-Type => content-Type fixed the error.

not work for me =(

Same issue, its only happening in android, iOS is fine.

Same issue here…

const fileExtension = coverImage.split(“.”).pop();

  // Create a new FormData instance
  const formData = new FormData();

  formData.append("image", {
    uri: coverImage,
    name: "image-" + new Date() + `.${fileExtension}`,
    type: `image/${fileExtension}`,
  } as any);

  // Append other form fields to FormData
  formData.append("food_name", data.food_name);
  formData.append("description", data.description);
  formData.append("price", String(data.price));
  formData.append("category", data.category);
  formData.append("addOn", JSON.stringify(data.addon));

  // Append sizes if applicable
  if (isSize && data.size.length > 0) {
    data.size.forEach((input, index) => {
      formData.append(`size[${index}]`, input.size);
      formData.append(`size_price[${index}]`, String(input.price));
    });
  }

  const response = await axios.post(
    `${app_url}/addMenuItem/${resId}`,
    formData,
    {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    }
  );

When I console.log req.file and req.body,

undefined [Object: null prototype] { food_name: ‘’, description: ‘’, price: ‘null’, category: ‘’, addOn: ‘{“addon”:“”,“price”:0}’ }

Here I’m not sending any data in req.body only sending file to req.file which I get undefined… This works fine with react native 0.73.x but not with 0.74.x

This issue still in

const formData = new FormData() formData.append(‘audio_file’, { name: fileName, type: ‘audio/mp3’, uri: filePath })

    await fetch('http endpoint', {
        body: formData,
        method: 'POST',
        headers: {
            'Content-Type': 'multipart/form-data',
            Authorization:
                'Bearer token'
        }
    })
        .then(res => {
            console.log('test result ', res)
            console.log('test result status ', res.status)
        })
        .catch(e => {
            console.log('test e ', e)
        })

This returns network error

REACT-NATIVE-INFO output:-

System: OS: macOS 14.2.1 CPU: (8) arm64 Apple M1 Memory: 599.88 MB / 16.00 GB Shell: version: “5.9” path: /bin/zsh Binaries: Node: version: 18.19.0 path: ~/.nvm/versions/node/v18.19.0/bin/node Yarn: version: 3.6.4 path: /opt/homebrew/bin/yarn npm: version: 10.2.3 path: ~/.nvm/versions/node/v18.19.0/bin/npm Watchman: version: 2024.04.15.00 path: /opt/homebrew/bin/watchman Managers: CocoaPods: version: 1.15.2 path: /opt/homebrew/bin/pod SDKs: iOS SDK: Platforms: - DriverKit 23.0 - iOS 17.0 - macOS 14.0 - tvOS 17.0 - watchOS 10.0 Android SDK: API Levels: - “27” - “28” - “29” - “30” - “31” - “32” - “33” - “34” Build Tools: - 27.0.3 - 28.0.3 - 29.0.2 - 29.0.3 - 30.0.2 - 30.0.3 - 31.0.0 - 32.0.0 - 32.1.0 - 33.0.0 - 33.0.0 - 33.0.1 - 34.0.0 System Images: - android-32 | Google APIs ARM 64 v8a - android-33 | Google APIs ARM 64 v8a Android NDK: Not Found IDEs: Android Studio: 2023.1 AI-231.9392.1.2311.11330709 Xcode: version: 15.0/15A240d path: /usr/bin/xcodebuild Languages: Java: version: 21.0.2 path: /usr/bin/javac Ruby: version: 2.6.10 path: /usr/bin/ruby npmPackages: “@react-native-community/cli”: Not Found react: installed: 18.2.0 wanted: 18.2.0 react-native: installed: 0.74.1 wanted: 0.74.1 react-native-macos: Not Found npmGlobalPackages: “react-native”: Not Found Android: hermesEnabled: true newArchEnabled: false iOS: hermesEnabled: true newArchEnabled: false