Skip to content

Upload & download progress ​

Live demo ​

Live demo · Upload

api.upload + multipart fields

Real api.upload() builds FormData and posts through createFetch from tanstack-fetch/sse. Add onUploadProgress in your app for XHR progress.

No file selected

0%

Pick a file and upload — real api.upload() + mock fetch

await api.upload('/files', {
  file,
  fieldName: 'file',
  fields: { folder: 'avatars', public: true },
  onUploadProgress: ({ progress }) => setProgress(progress),
})

Upload ​

ts
import { createFetch } from 'tanstack-fetch/sse'

const api = createFetch({ baseUrl: import.meta.env.VITE_API_URL })

await api.upload('/files', {
  file,
  fields: { albumId: '1' },
  onUploadProgress: ({ progress, loaded, total }) => {
    setProgress(progress ?? 0)
    console.log(loaded, total)
  },
})

Or build FormData yourself:

ts
import { createFormData } from 'tanstack-fetch'

const body = createFormData({ file, fields: { albumId: '1' } })
await api.post('/files', { body, onUploadProgress: … })

Download ​

ts
const blob = await api.get('/files/report.pdf', {
  parseAs: 'blob',
  onDownloadProgress: ({ progress, loaded, total }) => {
    setProgress(progress ?? 0)
    console.log(loaded, '/', total)
  },
})

// e.g. trigger a browser save
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = 'report.pdf'
link.click()
URL.revokeObjectURL(url)

Works on any method (get / post / …) — same options object:

ts
await api.post('/export', {
  body: { format: 'csv' },
  parseAs: 'blob',
  onDownloadProgress: ({ progress }) => setProgress(progress ?? 0),
})

Notes ​

  • upload() and progress events need createFetch from tanstack-fetch/sse (or /live, or a framework provider). The slim core tanstack-fetch client has no upload() and ignores onUploadProgress / onDownloadProgress.
  • Progress uses XHR under the hood when onUploadProgress and/or onDownloadProgress is set (fetch has no reliable progress API).
  • progress is loaded / total when Content-Length (download) or the upload size is known; otherwise only loaded updates.
  • Browser-only — on the server, omit these handlers and use plain fetch.

Example: examples/file-upload

MIT Licensed · Created by Mohammad Garmabi · Not an official TanStack package