Uploading a file in NestJS does not go through


I wanna upload a File from my React Native App to my API Endpoint that is written in NestJS.
I am using the fastify adapter with the fastify-multipart package.

This is how I send the file to my API:

  const data = new FormData();
  const file = new File([blob], "image1");

  console.log(file.size);

  data.append("file", file);

  const result = await axios
    .post("https://myapiurl/settings/upload-avatar", data, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    })

The console log above brings the following output for an example .png 1210126, so that means in my eyes that the file is correct and the problem lies in the backend.

This is my controller function for the endpoint:

  @Post('upload-avatar')
  async uploadAvatar(@Req() req: fastify.FastifyRequest,@Res() res: fastify.FastifyReply<any>) {
    const parts = req.parts();

    for await (const part of parts) {
      if (part.file) {
        const buffer = await part.toBuffer();
        console.log(buffer.length, buffer.byteLength)
      }
    }

    console.log("done");
  }

I tried around a lot but the end result is always that the buffer length is 0 and I basicly receive an empty file in my backend.

Source: JavaSript – Stack Overflow

November 26, 2021
Category : News
Tags: javascript | nestjs | typescript

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.