Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Native expo POST Blob

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

like image 482
Axel Ros Avatar asked Feb 25 '21 16:02

Axel Ros


1 Answers

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

}

like image 57
Axel Ros Avatar answered Oct 16 '22 07:10

Axel Ros