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

response json (5)



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

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

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

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

需要省略Fetch请求的 content-type 标头。 然后浏览器将自动添加包含表格边界的 Content type 标题

Content-Type: multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD


如果你想要 多个 文件,你可以使用它

var input = document.querySelector('input[type="file"]')

var data = new FormData()
for (const file of input.files) {

fetch('/avatars', {
  method: 'POST',
  body: data


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

要提交单个文件,您可以直接使用 input.files 数组中的 File 对象作为 body: 的值 body:fetch() 初始值设定项中:

const myInput = document.getElementById('my-input');

// Later, perhaps in a form 'submit' handler or the input's 'change' handler:
fetch('', {
  method: 'POST',
  body: myInput.files[0],

这是因为 File 继承自 Blob ,而 Blob 是获取标准中定义的允许的 BodyInit 类型之一。

这是带注释的基本示例。 您正在寻找 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('', { // 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
    response => response.json() // if the response is a JSON object
    success => console.log(success) // Handle the success response object
    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);