unstable_parseMultipartFormData
允许你为应用处理多部分表单(文件上传)。
¥Allows you to handle multipart forms (file uploads) for your app.
理解 浏览器文件 API 有助于了解如何使用此 API。
¥It would be useful to understand the Browser File API to know how to use this API.
它将代替 request.formData()
使用。
¥It's to be used in place of request.formData()
.
- const formData = await request.formData();
+ const formData = await unstable_parseMultipartFormData(request, uploadHandler);
例如:
¥For example:
export const action = async ({
request,
}: ActionFunctionArgs) => {
const formData = await unstable_parseMultipartFormData(
request,
uploadHandler // <-- we'll look at this deeper next
);
// The returned value for the file field is whatever our uploadHandler returns.
// Let's imagine we're uploading the avatar to s3,
// so our uploadHandler returns the URL.
const avatarUrl = formData.get("avatar");
// update the currently logged in user's avatar in our database
await updateUserAvatar(request, avatarUrl);
// success! Redirect to account page
return redirect("/account");
};
export default function AvatarUploadRoute() {
return (
<Form method="post" encType="multipart/form-data">
<label htmlFor="avatar-input">Avatar</label>
<input id="avatar-input" type="file" name="avatar" />
<button>Upload</button>
</Form>
);
}
要读取上传文件的内容,请使用它从 Blob API 继承的方法之一。例如,.text()
异步返回文件的文本内容,而 .arrayBuffer()
返回二进制内容。
¥To read the contents of an uploaded file, use one of the methods it inherits from the Blob API. For example, .text()
asynchronously returns the text contents of the file, and .arrayBuffer()
returns the binary contents.
uploadHandler
uploadHandler
是整个过程的关键。它负责处理从客户端流式传输 multipart/form-data 部分时的处理。你可以将其保存到磁盘、内存中,或者充当代理将其发送到其他地方(例如文件存储提供商)。
¥The uploadHandler
is the key to the whole thing. It's responsible for what happens to the multipart/form-data parts as they are being streamed from the client. You can save it to disk, store it in memory, or act as a proxy to send it somewhere else (like a file storage provider).
Remix 提供两个实用程序来为你创建 uploadHandler
:
¥Remix has two utilities to create uploadHandler
s for you:
unstable_createFileUploadHandler
unstable_createMemoryUploadHandler
这些是功能齐全的实用程序,用于处理相当简单的用例。除了非常小的文件外,不建议将任何其他文件加载到内存中。对于许多用例来说,将文件保存到磁盘是一种合理的解决方案。但是,如果你想将文件上传到文件托管服务提供商,则需要自己编写一个文件托管服务提供商。
¥These are fully featured utilities for handling fairly simple use cases. It's not recommended to load anything but quite small files into memory. Saving files to disk is a reasonable solution for many use cases. But if you want to upload the file to a file hosting provider, then you'll need to write your own.