React-Native 博览会 POST Blob

Axe*_*Ros 9 javascript typescript react-native expo

我在 expo 中使用 react native,我正在尝试通过 fetch api 发布 blob 图像。我正在为正文使用表单数据格式,并且我有下一个代码:

       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)
        })
Run Code Online (Sandbox Code Playgroud)

响应从未发生,我的控制台显示“FETCH ERROR [TypeError: Network request failed]”。任何的想法?

之前的感谢

Axe*_*Ros 16

终于我找到了灵魂。

我不知道为什么react-natvie expo应用程序不支持获取blob。但您可以使用以下方法替换 blob:

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

输入 3 个参数很重要,以避免 android 和 ios 出现错误。

就我而言,我的最终解决方案如下所示:

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)
})
Run Code Online (Sandbox Code Playgroud)

}

  • 此外,如果您仍然无法在服务器上接收图像,请关闭“调试远程 JS”。我花了几个小时试图找出为什么我在关闭 React Native Debugger 之前收不到图像。调试器以某种方式拦截或损坏了对服务器的请求。 (2认同)