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

新手上路,请多包涵

我仍然试图绕过它。

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

<form>
  <div>
    <label>Select file to upload</label>
    <input type="file">
  </div>
  <button type="submit">Convert</button>
</form>

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

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

原文由 deitch 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

这是一个带有注释的基本示例。 upload 功能就是你要找的:

 // 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);

原文由 Damien 发布,翻译遵循 CC BY-SA 4.0 许可协议

我是这样做的:

 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
})

原文由 Integ 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题