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 needcreateFetchfromtanstack-fetch/sse(or/live, or a framework provider). The slim coretanstack-fetchclient has noupload()and ignoresonUploadProgress/onDownloadProgress.- Progress uses XHR under the hood when
onUploadProgressand/oronDownloadProgressis set (fetch has no reliable progress API). progressisloaded / totalwhenContent-Length(download) or the upload size is known; otherwise onlyloadedupdates.- Browser-only — on the server, omit these handlers and use plain
fetch.
Example: examples/file-upload
