What's the process for sending files via JavaScript's fetch API?

I’m trying to figure out how to use the fetch API in JavaScript to upload files. Here’s what I’ve got so far:

<form>
  <div>
    <label>Choose file for upload</label>
    <input type="file" id="fileInput">
  </div>
  <button type="submit">Upload</button>
</form>

I can grab the file input and handle the form submission. But I’m stuck on how to actually send the file with fetch. My attempt looks like this:

document.querySelector('form').addEventListener('submit', function(e) {
  e.preventDefault();
  const file = document.getElementById('fileInput').files[0];
  
  fetch('/upload', {
    method: 'POST',
    // What should I put here for the body and headers?
  })
  .then(response => console.log('File uploaded'))
  .catch(error => console.error('Upload failed', error));
});

Can someone explain what I need to add to make this work? I’m not sure about the body and headers for sending files.

To send files with fetch, you need to use FormData. Here’s how to modify your code:

document.querySelector('form').addEventListener('submit', function(e) {
  e.preventDefault();
  const file = document.getElementById('fileInput').files[0];
  const formData = new FormData();
  formData.append('file', file);
  
  fetch('/upload', {
    method: 'POST',
    body: formData
  })
  .then(response => response.json())
  .then(data => console.log('File uploaded:', data))
  .catch(error => console.error('Upload failed:', error));
});

This approach automatically sets the correct Content-Type header. Make sure your server is set up to handle multipart/form-data requests for file uploads.

Hey, I’ve dealt with file uploads using fetch before, and it’s not as tricky as it seems. The key is using FormData. Here’s what worked for me:

const form = document.querySelector('form');
form.addEventListener('submit', async (e) => {
  e.preventDefault();
  const fileInput = document.getElementById('fileInput');
  const formData = new FormData();
  formData.append('file', fileInput.files[0]);

  try {
    const response = await fetch('/upload', {
      method: 'POST',
      body: formData
    });
    if (!response.ok) throw new Error('Upload failed');
    const result = await response.json();
    console.log('Upload successful:', result);
  } catch (error) {
    console.error('Error:', error);
  }
});

This approach worked like a charm for me. Just make sure your server can handle multipart/form-data. Also, don’t set the Content-Type header manually - the browser handles that automatically with FormData. Good luck with your upload feature!

hey there! for file uploads with fetch, you’ll wanna use formdata. here’s a quick example:

const formData = new FormData();
formData.append('file', fileInput.files[0]);

fetch('/upload', {
  method: 'POST',
  body: formData
})

don’t set content-type header, browser handles it. hope this helps!