fastify / fastify

Fast and low overhead web framework, for Node.js

Home Page:https://www.fastify.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Upload file always raises error FST_ERR_CTP_INVALID_CONTENT_LENGTH

hoangdev01 opened this issue · comments

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

^4.18.0

Plugin version

^4.5.0

Node.js version

18.19.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

14.3.1

Description

Cannot upload file

Steps to Reproduce

Can you help me, please!

My code:

import fastify from 'fastify';
import multipart from '@fastify/multipart';
import {
  S3Client,
  PutObjectCommand,
} from '@aws-sdk/client-s3';
import { fromEnv } from '@aws-sdk/credential-provider-env';

const server = fastify();
server.register(multipart);

const s3 = new S3Client({
  region: process.env.AWS_REGION,
  credentials: fromEnv(),
});
const generateFileName = (key: string) => `${key}-${Date.now()};

server.post('/upload', {bodyLimit: 10 * 1024 * 1024}, async (req, reply) => {
  let data: any = await req.file();
  data = await data.toBuffer();

  if(!data) return null;

  const key = generateFileName(data.filename);

  const putObjectCommand = new PutObjectCommand({
    Bucket: process.env.AWS_BUCKET, 
    Key: key,
    Body: await data.toBuffer(),
    ContentType: data.mimetype,
  });

  await s3.send(putObjectCommand);
  reply.send(`File uploaded successfully. ${data.Location}`);
});

server.listen(3000);

I sent the request using postman with content-type is application/json and added 1 file (image) to the binary section and then the result received is the error:

{
    "statusCode": 400,
    "code": "FST_ERR_CTP_INVALID_CONTENT_LENGTH",
    "error": "Bad Request",
    "message": "Request body size did not match Content-Length"
}

image
image
If I leave out the bodylimit then of course the error code will be:

{
    "statusCode": 413,
    "code": "FST_ERR_CTP_BODY_TOO_LARGE",
    "error": "Payload Too Large",
    "message": "Request body is too large"
}

image
I can't debug because the error is raised before it even reaches the preHandler function.

Expected Behavior

Uploaded photos should be saved on my s3 or at least it can reach the handler function.

You can’t send a file as binary with json like that 😄

Please try Content-Type: multipart/form-data

Oh, thank you very much, I fixed it.
I was focusing on the wrong point so the research failed before :(
I need to study more!
Thank you