在您的 React Router 应用程序中处理文件上传。本指南使用来自 Remix The Web 项目的一些包来简化文件上传。
感谢 David Adams 撰写了原始指南,本文档基于此指南。您可以参考它以获取更多示例。
您可以根据需要设置路由。此示例使用以下结构
import {
type RouteConfig,
route,
} from "@react-router/dev/routes";
export default [
// ... other routes
route("user/:id", "pages/user-profile.tsx", [
route("avatar", "api/upload-avatar.tsx"),
]),
] satisfies RouteConfig;
form-data-parser
是 request.formData()
的一个包装器,提供用于处理文件上传的流式支持。
npm i @mjackson/form-data-parser
请参阅 form-data-parser
文档以获取更多信息
parseFormData
函数接受一个 uploadHandler
函数作为参数。此函数将在表单中的每个文件上传时被调用。
您必须将表单的 enctype
设置为 multipart/form-data
才能使文件上传正常工作。
import {
type FileUpload,
parseFormData,
} from "@mjackson/form-data-parser";
export async function action({
request,
}: ActionFunctionArgs) {
const uploadHandler = async (fileUpload: FileUpload) => {
if (fileUpload.fieldName === "avatar") {
// process the upload and return a File
}
};
const formData = await parseFormData(
request,
uploadHandler
);
// 'avatar' has already been processed at this point
const file = formData.get("avatar");
}
export default function Component() {
return (
<form method="post" encType="multipart/form-data">
<input type="file" name="avatar" />
<button>Submit</button>
</form>
);
}
file-storage
是一个用于存储 文件对象 的键值接口,使用 JavaScript 实现。类似于 localStorage
允许您在浏览器中存储字符串的键值对,file-storage
允许您在服务器上存储文件的键值对。
npm i @mjackson/file-storage
创建一个文件,导出一个 LocalFileStorage
实例,供不同的路由使用。
import { LocalFileStorage } from "@mjackson/file-storage/local";
export const fileStorage = new LocalFileStorage(
"./uploads/avatars"
);
export function getStorageKey(userId: string) {
return `user-${userId}-avatar`;
}
更新表单的 action
以将文件存储在 fileStorage
实例中。
import {
FileUpload,
parseFormData,
} from "@mjackson/form-data-parser";
import {
fileStorage,
getStorageKey,
} from "~/avatar-storage.server";
import type { Route } from "./+types/user-profile";
export async function action({
request,
params,
}: Route.ActionArgs) {
async function uploadHandler(fileUpload: FileUpload) {
if (
fileUpload.fieldName === "avatar" &&
fileUpload.type.startsWith("image/")
) {
let storageKey = getStorageKey(params.id);
// FileUpload objects are not meant to stick around for very long (they are
// streaming data from the request.body); store them as soon as possible.
await fileStorage.set(storageKey, fileUpload);
// Return a File for the FormData object. This is a LazyFile that knows how
// to access the file's content if needed (using e.g. file.stream()) but
// waits until it is requested to actually read anything.
return fileStorage.get(storageKey);
}
}
const formData = await parseFormData(
request,
uploadHandler
);
}
export default function UserPage({
actionData,
params,
}: Route.ComponentProps) {
return (
<div>
<h1>User {params.id}</h1>
<form
method="post"
// The form's enctype must be set to "multipart/form-data" for file uploads
encType="multipart/form-data"
>
<input type="file" name="avatar" accept="image/*" />
<button>Submit</button>
</form>
<img
src={`/user/${params.id}/avatar`}
alt="user avatar"
/>
</div>
);
}
创建一个 资源路由,将文件作为响应流式传输。
import {
fileStorage,
getStorageKey,
} from "~/avatar-storage.server";
import type { Route } from "./+types/upload-avatar";
export async function loader({ params }: Route.LoaderArgs) {
const storageKey = getStorageKey(params.id);
const file = await fileStorage.get(storageKey);
if (!file) {
throw new Response("User avatar not found", {
status: 404,
});
}
return new Response(file.stream(), {
headers: {
"Content-Type": file.type,
"Content-Disposition": `attachment; filename=${file.name}`,
},
});
}