File Operations in JavaScript

From the Fetch API cheat sheet · Advanced Features · verified Jul 2026

File Operations

Uploading files and handling downloads with progress

javascript
// Single file upload
const fileInput = document.getElementById('file')
const file = fileInput.files[0]

const formData = new FormData()
formData.append('file', file)
formData.append('description', 'Profile photo')

const response = await fetch('/api/upload', {
  method: 'POST',
  body: formData
})

// Multiple files
const formData = new FormData()
for (const file of fileInput.files) {
  formData.append('files[]', file)
}

// Download file
async function downloadFile(url, filename) {
  const response = await fetch(url)
  const blob = await response.blob()
  
  const downloadUrl = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = downloadUrl
  a.download = filename
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(downloadUrl)
}
📌 FormData automatically sets multipart/form-data header
⚠️ Fetch doesn't support upload progress - use XMLHttpRequest
💡 Chunk large files to avoid memory issues
⚡ Use Range headers for resumable downloads

More JavaScript tasks

Back to the full Fetch API cheat sheet