使用React-Native Fetch API通过HTTP发送二进制文件

Ark*_*kon 5 http request fetch http-headers react-native

有没有一种使用Fetch API上载二进制文件的方法(例如,使用签名URL上载到S3)?

对于某些“应用程序/八位字节流”,这将是一个简单的PUT。

XHR库正在运行,但是我相信Fetch更好,尤其是在React-Native环境中。现在,
React-Native Fetch是否支持Blob

理想情况下,我想执行以下操作,但Blob未定义:

fetch('https://s3.amazonaws.com/signedUrl/', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/octet-stream',
  },
  body: Blob(filePath)
})
Run Code Online (Sandbox Code Playgroud)

Cor*_*che -3

我建议使用: https: //github.com/github/fetch作为 Fetch 的 polyfill,因为没有得到广泛支持。

获取文档样本:

var input = document.querySelector('input[type="file"]')

var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')

fetch('/avatars', {
  method: 'POST',
  body: data
})
Run Code Online (Sandbox Code Playgroud)

我使用它如下:

var input = document.querySelector('input[type="file"]')

function upload(e) {
  const file = input.files[0];
  const reader = new FileReader();

  reader.onload = (e) => { 
    fetch('/avatars', {
      method: 'POST',
      body: e.currentTarget.result
    })
  };

  reader.readAsArrayBuffer(file);
}

input.addEventListener('change', upload, false)
Run Code Online (Sandbox Code Playgroud)

  • React Native 与移动开发相关,而不是 Web。移动设备上没有`input[type="file"]`,只是使用普通的`XMLHttpRequest`对象来发送请求。 (2认同)