【问题标题】:Sending binary through HTTP with React-Native Fetch API使用 React-Native Fetch API 通过 HTTP 发送二进制文件
【发布时间】:2017-04-27 23:26:22
【问题描述】:

有没有办法使用 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)
})

【问题讨论】:

    标签: http react-native request http-headers fetch


    【解决方案1】:

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

    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 上的示例 pathToFilefile:///Users/username/Library/Developer/CoreSimulator/Devices/061D4A47-6363-4996-A157-03E6AD2DD9E4/data/Containers/数据/应用程序/3900F3EF-3259-43CF-9400-87B638EF9A1B/库/缓存/相机/F86E7345-080A-4D51-A80E-0CAD3370A353.jpg

    【讨论】:

      【解决方案2】:

      我建议使用: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
      })
      

      我是这样使用的:

      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)
      

      【讨论】:

      • React Native 与移动开发相关,而不是 web。移动设备上没有input[type="file"],只是普通的XMLHttpRequest对象用于发送请求。
      猜你喜欢
      • 2012-01-02
      • 2014-03-31
      • 1970-01-01
      • 1970-01-01
      • 2017-01-27
      • 1970-01-01
      • 2012-02-18
      • 2021-08-16
      • 2021-09-28
      相关资源
      最近更新 更多