unstable_parseMultipartFormData
允許您處理應用程式的多部分表單(檔案上傳)。
了解 瀏覽器檔案 API 將有助於您了解如何使用此 API。
它用於取代 request.formData()
。
- const formData = await request.formData();
+ const formData = await unstable_parseMultipartFormData(request, uploadHandler);
例如
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()
會傳回二進位內容。
uploadHandler
uploadHandler
是整個過程的關鍵。它負責處理從客戶端串流傳輸的多部分/表單資料部分。您可以將其儲存到磁碟、儲存在記憶體中,或作為代理將其傳送到其他地方(例如檔案儲存提供者)。
Remix 有兩個實用程式可以為您建立 uploadHandler
unstable_createFileUploadHandler
unstable_createMemoryUploadHandler
這些是功能完善的實用程式,適用於處理相當簡單的使用案例。不建議將任何較大的檔案載入記憶體中。將檔案儲存到磁碟對於許多使用案例來說是合理的解決方案。但是,如果您想將檔案上傳到檔案託管提供者,則需要編寫自己的程式。