网站搜索

typescript - 使用 Fastify 的 Busboy 报错 Unsupported Media Type: multipart/form-data; boundary


我正在尝试在 Fastify 中使用 BusBoy 上传文件

但是我收到了这个错误

Unsupported Media Type: multipart/form-data; boundary=--------------------------964469693542161018443025
    reqId: "req-1"
    res: {
      "statusCode": 415
    }
    err: {
      "type": "FastifyError",
      "message": "Unsupported Media Type: multipart/form-data; boundary=--------------------------964469693542161018443025",
      "stack":
          FastifyError: Unsupported Media Type: multipart/form-data; boundary=--------------------------964469693542161018443025
              at ContentTypeParser.run 

上传功能看起来是这样的....

import Busboy from "busboy";

async function uploadFile(fastify: any, _options: Object) {

  fastify.post(
    "/v1/uploads/uploadFile",
    postOpts,
    async function (request: any, reply: any) {
      const bb = Busboy({
        headers: request.headers,
        preservePath: true,
        limits: { fileSize: 100000 },
      });
      bb.on(
        "file",
        (
          fieldname: any,
          file: any,
          filename: any,
          encoding: any,
          mimetype: any
        ) => {
          console.log(fieldname, file, filename, encoding, mimetype);

          request.pipe(bb);
        }
      );
     

      const statusCode: number = 201;
      reply
        .code(statusCode)
        .header("Server-Timing", createServerTiming(serverTiming))
        .header("Content-Type", "application/json; charset=utf-8")
        .send({ statusCode });
    }
  );
}

const postOpts = {
  schema: {
    summary: "Upload File",
    consumes: ["multipart/form-data"],
    response: {
      200: {
        type: "object",
        description:
          "The request was successful. The response will contain a JSON body.",
        properties: {
          uploadConfirmed: { type: "boolean" },
        },
      },
      400: {
        type: "object",
        description: "The request was invalid and/or malformed.",
        properties: {
          error: { type: "string" },
          statusCode: { type: "number" },
          message: { type: "string" },
        },
      },
      500: {
        type: "object",
        description: "There was an internal error.",
        properties: {
          error: { type: "string" },
          statusCode: { type: "number" },
          message: { type: "string" },
        },
      },
    },
  } as const,
};

export { uploadFile };

这里是 Fastify Busboy 的文档

答案#1

HTTP 请求解析发生在 fastify 的内容类型解析器组件中。

你需要这样设置:

fastify.addContentTypeParser('multipart', myBusboyImplementation)

function myBusboyImplementation (request, payload, done) {
  // payload is the request stream where you can listen for `data` events
  done(null, 'my parsed payload')
}

请注意,这已经由 @fastify/multipart 实现,但您可以根据需要自行实现