文件上传
处理文件上传。
网络上的文件上传通常是通过提交 POST 请求和包含文件的 FormData 主体来完成的。你可以使用拦截的 Fetch API Request 实例上的 formData() 方法拦截该请求并将其正文读取为 FormData。
¥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(),
})
}),
]你可以以任何你喜欢的方式发出文件上传。下面是一个使用 JavaScript 中的纯 fetch() 函数将纯文本 doc.txt 文档发送到服务器的示例:
¥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,
})
FormData和Blob都是浏览器和 Node.js 中的标准 API。你还可以使用FileAPI 来描述文件。¥Both
FormDataandBlobare standard APIs in the browser and Node.js. You can also use theFileAPI to describe files.