0
0
JavascriptHow-ToBeginner · 3 min read

How to Upload File Using Fetch in JavaScript Easily

To upload a file using fetch in JavaScript, create a FormData object, append the file to it, and send it as the body of a fetch POST request. This lets you send files easily to a server endpoint.
📐

Syntax

Use fetch with a POST method and a FormData object containing the file. The FormData handles encoding the file for upload.

  • url: The server endpoint to receive the file.
  • method: Usually POST for uploads.
  • body: A FormData object with the file appended.
javascript
const formData = new FormData();
formData.append('file', fileInput.files[0]);

fetch('https://example.com/upload', {
  method: 'POST',
  body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
💻

Example

This example shows how to upload a file selected from an HTML file input to a server using fetch. It logs the server response or error.

javascript
const fileInput = document.querySelector('#fileInput');
const uploadButton = document.querySelector('#uploadButton');

uploadButton.addEventListener('click', () => {
  const file = fileInput.files[0];
  if (!file) {
    console.log('No file selected');
    return;
  }

  const formData = new FormData();
  formData.append('file', file);

  fetch('https://httpbin.org/post', {
    method: 'POST',
    body: formData
  })
  .then(response => response.json())
  .then(data => console.log('Upload successful:', data))
  .catch(error => console.error('Upload error:', error));
});
Output
Upload successful: { ...server response JSON... }
⚠️

Common Pitfalls

  • Not using FormData causes the file to not upload correctly.
  • Setting Content-Type header manually when using FormData breaks the request; let the browser set it.
  • Forgetting to check if a file is selected before uploading.
javascript
/* Wrong way: setting Content-Type manually breaks upload */
const formData = new FormData();
formData.append('file', fileInput.files[0]);

fetch('https://example.com/upload', {
  method: 'POST',
  headers: { 'Content-Type': 'multipart/form-data' }, // ❌ Don't do this
  body: formData
});

/* Right way: omit Content-Type header */
fetch('https://example.com/upload', {
  method: 'POST',
  body: formData
});
📊

Quick Reference

  • Use FormData to wrap files for upload.
  • Send FormData as body in fetch with POST method.
  • Do not set Content-Type header manually when using FormData.
  • Always check if a file is selected before uploading.

Key Takeaways

Use FormData to send files with fetch for proper encoding.
Do not manually set Content-Type header when sending FormData.
Always check if a file is selected before uploading.
Use fetch with POST method and FormData as the request body.
Handle server responses and errors with then/catch.