Search code examples
react-nativefetchform-data

Uploading image using the fetch call and get Network request failed


I'm trying to upload an image using the fetch call bellow and I keep getting the following error:

Network request failed
at node_modules\whatwg-fetch\dist\fetch.umd.js:535:17 in setTimeout$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:123:14 in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:379:16 in callTimers
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:414:4 in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:113:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:365:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112:4 in callFunctionReturnFlushedQueue

When I remove the file from the formData it works fine. I've read all the relevant posts on here and nothing works for me. I've tried uploading the file using axios but that didn't work either because of some formdata-axios incompatibilities for the newer react-native versions. The uri is not the problem cause I'm testing on android and not on ios where thee "file://" would have to be removed.

        const data = new FormData();
        data.append("file", {
                        uri: result.uri,
                        type: "image/jpg",
                        name: "photo.jpg",
        });
        data.append("user", "test");

        res = await fetch("https://modern-zebra-85.loca.lt/api/process", {
          method: "POST",
          headers: {
            Accept: "application/json",
            "Content-Type": "multipart/form-data",
          },
          body: data,
        })
          .then((result) => console.log(result))
          .catch((err) => console.log(err));

Solution

  • Solved it, I was using localtunnel to be able to run the app using a public url and hosting the server locally (so that I could access the results) and probably localtunnel doesn't transfer files. I assume that because once I tried posting on the live version of my server everything worked fine.