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

2023-12-14

我仍在努力解决这个问题。

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

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

我是这样做的:

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
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 JS fetch API 上传文件? 的相关文章

随机推荐