Nestjs receives POSTed image files from Nextjs.

When posting multiple image files from Nextjs and receiving them in the Nestjs Controller, I was confused about how to receive them, so I wrote this down.

目次

POST image File from Nextjs.

Keep File as useState.
Store multiple images as an array as File[].

const [images, setImages] = useState<File[]>([])

The File[] held in images is passed to the fetcher function.

In the POST, the parameters (params) and the image file (images) should be included in the Body.
AccessToken and keys required for the API can be added to the arguments as required.

The point is that the API receiver wants to receive image files in an array, so images:File[] needs to be stored in FormData in file units.

export const postImages = async (
  accessToken: string,
  params: ParamsDataType,
  images: File[]
): Promise<responseInterface<void>> => {
  const formData = new FormData()

  for (const [key, value] of Object.entries(images)) {
    formData.append('imageFiles', value)
  }

  formData.append('postData', JSON.stringify(params))

  return await fetcher(`${process.env.NEXT_PUBLIC_API_BASE_URL}/post`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${accessToken}`
    },
    body: formData
  })
}

The fetcher function uses the Fetch API.

export const fetcher = async (resource: RequestInfo, init?: RequestInit): Promise<any> => {
  try {
    const res = await fetch(resource, init)
    return Object.assign(await res.json(), { statusCode: res.status })
  } catch {
    throw new Error()
  }
}

Get ImageFile from Nestjs.

To receive images, use the FileFieldsInterceptor decorator.

The FileFieldsInterceptor decorator takes a name property as an argument, which must match the key name in the FormData of the POSTing party.
When using the FileFieldsInterceptor decorator, use the UploadedFiles decorator to extract files from the request.

This way, the parameters and files that have been POSTed can be retrieved.

@POST() decorator to accept POSTs.
@ApiBearerAuth() In @ApiBearerAuth(), include authentication in Nestjs if you have it.

  @POST()
  @ApiBearerAuth()
  @ApiProduces('charset=utf-8')
  @UseInterceptors(FileFieldsInterceptor([{ name: 'imageFiles' }]))
  async postMethod(
    @Body() data: { postData: string },
    @UploadedFiles()
    files: {
      imageFiles: Express.Multer.File[];
    },
  ): Promise<void> {
    const postData = JSON.parse(data.postData);
    const imageFiles = files.imageFiles;
  }

The official Nestjs file upload is here.

Summary

When POST does not work, it is necessary to start by determining which is the cause, the front-end or the back-end.
In this case, attaching the file with POSTMAN and hitting the back-end API worked, so by reviewing how to hit the API from the front-end, Nestjs is now able to receive the image file POSTed from Nextjs.

よかったらシェアしてね!
目次