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

3 Answers

这是一个带注释的基本示例。 您正在寻找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": "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);
fetch上传文件 fetch阮一峰



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


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类型之一。


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

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

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


javascript fetch