- Introduction
- Getting started
- Philosophy
- Comparison
- Limitations
- Debugging runbook
- FAQ
- Basics
- Concepts
- Network behavior
- Integrations
- API
- CLI
- Best practices
- Recipes
- Cookies
- Query parameters
- Response patching
- Polling
- Streaming
- Network errors
- File uploads
- Responding with binary
- Custom worker script location
- Global response delay
- GraphQL query batching
- Higher-order resolver
- Keeping mocks in sync
- Merging Service Workers
- Mock GraphQL schema
- Using CDN
- Using custom "homepage" property
- Using local HTTPS
File uploads
Handle file uploads.
File uploads on the web are usually done by submitting a POST request with a FormData body containing the files. You can intercept that request and read its body as FormData using the formData() method on the intercepted Fetch API Request instance.
import { http, HttpResponse } from 'msw'
export const handlers = [
http.post('/upload', async ({ request }) => {
const data = await request.formData()
const file = data.get('file')
if (!file) {
return new HttpResponse('Missing document', { status: 400 })
}
if (!(file instanceof File)) {
return new HttpResponse('Uploaded document is not a File', {
status: 400,
})
}
return HttpResponse.json({
contents: await file.text(),
})
}),
]You can issue the file upload in any way you prefer. Here’s an example of using the plain fetch() function in JavaScript that sends a plain text doc.txt document to the server:
const data = new FormData()
const file = new Blob(['Hello', 'world'], { type: 'text/plain' })
data.set('file', file, 'doc.txt')
fetch('/upload', {
method: 'POST',
body: data,
})Both
FormDataandBlobare standard APIs in the browser and Node.js. You can also use theFileAPI to describe files.