9
votes

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

1
You can convert it to base64 and upload the base64. If you don't want to use base64, you can use rn-fetch-blob - Uğur Eren
Thx for your answer! But i'm using Expo and it seems that rn-fetch-blob is not supported by expo. - Axel Ros
I am quite sure, the issue is with the headers, could you please update your code what all headers you are using? - Himanshu Saxena
@AxelRos Please add your expo SDK version along with the platform where you are getting this issue. - Waheed Akhtar

1 Answers

2
votes

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)
})

}