【问题标题】:What is the Fetch API equivalent of XMLHttpRequest.send(file)?什么是 XMLHttpRequest.send(file) 的 Fetch API 等价物?
【发布时间】:2016-08-04 22:20:19
【问题描述】:

我正在尝试将客户端从 XMLHttpRequest 重构为旧后端,以改用 Fetch API,但我很难弄清楚下面代码中与 xhr.send(file) 等效的 Fetch API 是什么。

input.addEventListener('change', function(event) {
  var file = event.target.files[0];
  var url = 'https://somedomain.com/someendpoint';
  var xhr = new XMLHttpRequest();
  xhr.open('POST', url, true);
  xhr.setRequestHeader('Content-Type', 'image/jpeg');
  xhr.send(file);
}

【问题讨论】:

    标签: javascript ajax html dom fetch-api


    【解决方案1】:

    这可以这样完成:

    var input = document.querySelector('input[type="file"]')
    
    var data = new FormData()
    data.append('file', input.files[0])
    
    fetch('/avatars', {
      method: 'POST',
      body: data
    })
    

    https://github.com/github/fetch

    https://developer.mozilla.org/en-US/docs/Web/API/FormData

    【讨论】:

    • 这是我在许多互联网站点上找到的方式,但并不等同。我已经尝试过了,但它不起作用。然而,Stas Malolepszy 的解决方案确实如此。
    【解决方案2】:

    fetch 可以采用second argumentinit,指定请求的高级选项。特别是,您可以指定 methodbody 选项:

    fetch(url, {
      method: 'POST',
      headers: new Headers({
        "Content-Type": "image/jpeg",
      }),
      body: file,
    })
    

    您也可以将相同的选项传递给Requestconstructor

    body 必须是 Blob、BufferSource、FormData、URLSearchParams 或 USVString 对象。幸运的是,File 对象只是一种特殊的 Blob,可以使用everywhere where Blobs are accepted

    【讨论】:

    • 你赢了!非常感谢。
    猜你喜欢
    • 2015-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 2014-05-08
    • 2014-06-12
    相关资源
    最近更新 更多