12

I'm using react native with expo and I'm trying to POST a blob image through fetch api. I'm using form-data format for the body and i have the next code:

       const blob = await response.blob()
       const form = new FormData()
        form.append('file', blob)
        const options: RequestInit = {
            method: 'POST',
            headers,
            body: form
        }
        return this.fetch(path, options).then(res => {
            console.log("FETCHING", res.status)
            this.processResponse(path, options, res)
        }).catch(err => {
            console.log("FETCH ERROR", err)
        })

Response never happens, and my console says "FETCH ERROR [TypeError: Network request failed]". Any idea?

Thanx from before hand

Axel Ros
  • 685
  • 1
  • 7
  • 15

1 Answers1

14

Finally i found a soultion.

I don't know why fetching a blob is not supported in react-natvie expo apps. But you can replace the blob using:

form.append('file', { uri, name: 'media', type: `image/${type}` } as any)

It's important to put 3 parameters in order to avoid errors for android and ios.

In my case my final solution looks like this:

async postMedia(path: string, uri: string) {
let type = uri.substring(uri.lastIndexOf(".") + 1);
const headers = await this.getHeaders('multipart/form-data')
const form = new FormData()
form.append('file', { uri, name: 'media', type: `image/${type}` } as any)
const options: RequestInit = {
  method: 'POST',
  headers,
  body: form
}
return this.fetch(path, options).then(res => {
  console.log("FETCH MEDIA", res)
  this.processResponse(path, options, res)
}).catch(err => {
  console.log("FETCH ERROR", err)
})

}

Axel Ros
  • 685
  • 1
  • 7
  • 15
  • 2
    Additionally, If you still can't receive your image on the server, turn off Debug Remote JS. I spent several hours trying to figure out why I don't receive images until I turned off React Native Debugger. Debugger somehow intercepted or corrupted requests to the server. – Black Beard Sep 24 '21 at 13:05
  • This did it for me. I've seen other SO answers that suggested passing in the `uri`, however, TypeScript said that there is no such field. I guess this is a TS bug? – Moshe G Dec 09 '21 at 18:14
  • awesome answer, I have stuck by the problem one day, you saved me, thank you – wangjun Jun 20 '22 at 13:17
  • Sometimes i forget how badly react-native is documented Here is relevant source: https://github.com/facebook/react-native/blob/90faf0f254fef89eface8d30b72402359991c67b/Libraries/Network/FormData.js#L31-L50 – MadRunner Oct 12 '22 at 11:46
  • Saved my day (3rd fighting with files)! – Arif Dewi Mar 07 '23 at 09:15