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




response json (5)

我仍然试图绕过它。

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

<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 发送文件?

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

https://code.i-harness.com


使用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) {
  data.append('files',file,file.name)
}

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('https://example.com/some_endpoint', {
  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('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);




fetch