返回
创建于
状态公开

trpc 提交 FormData 和 二进制文件的解决办法

https://trpc.io/docs/server/non-json-content-types

Non-JSON Content Types

In addition to JSON-serializable data, tRPC can be used with FormData, File, and other Binary types

FormData Input

FormData is natively supported, and for more advanced usage you could also combine this with a library like zod-form-data to validate inputs in a type-safe way.

ts
1// Our examples use Zod by default, but usage with other libraries is identical
2import { z } from 'zod';
3 
4export const t = initTRPC.create();
5const publicProcedure = t.procedure;
6 
7export const appRouter = t.router({
8  hello: publicProcedure.input(z.instanceof(FormData)).query((opts) => {
9    const data = opts.input; // const data: FormData
10    return {
11      greeting: `Hello ${data.get('name')}`,
12    };
13  }),
14});

File and other Binary Type Inputs

tRPC converts many octet content types to a ReadableStream which can be consumed in a procedure. Currently these are Blob Uint8Array and File but more can be added easily.

ts
1import { octetInputParser } from '@trpc/server/http';
2 
3export const t = initTRPC.create();
4const publicProcedure = t.procedure;
5 
6export const appRouter = t.router({
7  upload: publicProcedure.input(octetInputParser).query((opts) => {
8    const data = opts.input; // const data: ReadableStream<any>
9    return {
10      valid: true,
11    };
12  }),
13});