I'm trying to use React Native to post an image to a remote API. In order to use fetch(...)
, I need to turn a public URL into a file object. I use the following code.
const getFile = async (url: string, fileName: string) => {
const response = await fetch(url, { method: "GET" });
const data = await response.blob();
const metadata = {
type: "image/jpeg",
};
const file = new File([data], fileName, metadata);
return file;
};
const myFile = await getFile("...IMG_URL...", "pic.jpg");
The above code works perfectly well in a browser console. But when I run it using React Native, I get a slightly different behavior. For instance, I can use console.log(myFile)
in browser, it prints the file. But, if I run console.log(myFile)
in React Native, it does not.
I need the picture to be in a file object because I need to use it in a subsequent fetch(...)
call:
const bodyData = new FormData();
bodyData.append("userId", "1");
bodyData.append("logId", "1");
bodyData.append("file", myFile);
const response = await fetch(
"...API_URL...",
{
method: "POST",
body: bodyData,
}
);
However, running this causes the following error, which I am unable to interpret:
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:130:14 in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:383:16 in callTimers
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:416:4 in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:109:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:108:4 in callFunctionReturnFlushedQueue
I know that this is not a problem with connecting to the server because if I run the same code without the "file"
header, it successfully connects to the API server.
It has been recommended that I use rn-fetch-blob
, but I can not do this because rn-fetch-blob
is not compatible with Expo.