首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用JS fetch API上传文件?

如何使用JS fetch API上传文件?
EN

Stack Overflow用户
提问于 2016-03-18 01:31:55
回答 11查看 247.6K关注 0票数 242

我还在努力想办法解决这个问题。

我可以让用户使用文件输入选择文件(甚至多个):

代码语言:javascript
复制
<form>
  <div>
    <label>Select file to upload</label>
    <input type="file">
  </div>
  <button type="submit">Convert</button>
</form>

我可以使用<fill in your event handler here>捕获submit事件。但是,一旦我这样做了,我如何使用fetch发送文件呢

代码语言:javascript
复制
fetch('/files', {
  method: 'post',
  // what goes here? What is the "body" for this? content-type header?
}).then(/* whatever */);
EN

回答 11

Stack Overflow用户

回答已采纳

发布于 2016-03-18 18:31:21

这是一个带有注释的基本示例。upload函数就是您要查找的函数:

代码语言:javascript
复制
// Select your input type file and store it in a variable
const input = document.getElementById('fileinput');

// This will upload the file after having read it
const upload = (file) => {
  fetch('http://www.example.net', { // Your POST endpoint
    method: 'POST',
    headers: {
      // Content-Type may need to be completely **omitted**
      // or you may need something
      "Content-Type": "You will perhaps need to define a content-type here"
    },
    body: file // This is your file object
  }).then(
    response => response.json() // if the response is a JSON object
  ).then(
    success => console.log(success) // Handle the success response object
  ).catch(
    error => console.log(error) // Handle the error response object
  );
};

// Event handler executed when a file is selected
const onSelectFile = () => upload(input.files[0]);

// Add a listener on your input
// It will be triggered when a file will be selected
input.addEventListener('change', onSelectFile, false);
票数 181
EN

Stack Overflow用户

发布于 2016-11-27 16:05:51

我是这样做的:

代码语言:javascript
复制
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
})
票数 287
EN

Stack Overflow用户

发布于 2018-03-27 18:49:54

使用Fetch API发送文件时的一个重要注意事项

需要省略Fetch请求的content-type头。然后,浏览器将自动添加包含Form边界的Content type标头,如下所示

代码语言:javascript
复制
Content-Type: multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD

表单边界是表单数据的分隔符。

票数 125
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36067767

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档