使用React-Native Fetch API通过HTTP发送二进制数据

6
有没有一种方法可以使用Fetch API上传二进制文件(例如使用签名URL上传到S3)?
对于某些“application/octet-stream”来说,这将是一个简单的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)
})
2个回答

0

如果您拥有二进制文件的文件系统路径,例如使用内置的XMLHttpRequest发送请求,此方法适用于Android/iOS和模拟器:

const xhr = new XMLHttpRequest();
xhr.open('post', serviceUrl);
xhr.onreadystatechange = () => {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      resolve(xhr.response);
    } else {
      reject(xhr.response);
    }
  }
};

xhr.setRequestHeader('Content-Type', 'image/jpeg');

xhr.send({ uri: 'pathToFile', type: 'image/jpeg', name: 'file' });

在 macOS 上,pathToFile 的示例是 file:///Users/username/Library/Developer/CoreSimulator/Devices/061D4A47-6363-4996-A157-03E6AD2DD9E4/data/Containers/Data/Application/3900F3EF-3259-43CF-9400-87B638EF9A1B/Library/Caches/Camera/F86E7345-080A-4D51-A80E-0CAD3370A353.jpg


-3
我建议使用https://github.com/github/fetch作为Fetch的polyfill,因为它并不被广泛支持。
Fetch文档示例:
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
})

我使用它的方式如下:
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)

2
React Native与移动开发相关,而非Web开发。在移动设备上,不存在input[type="file"],只能使用普通的XMLHttpRequest对象来发送请求。 - rudyryk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接