Maxiss
Maxiss

Reputation: 1056

Multipart: Boundary not found - upload file (using multer)

I am using multer to upload file, it seems to work on the api side but here is the issue on the front side:

fetch(`${path}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    body: file,
  }).then((response) => {
    return response.status;
  });

If I add 'multipart/form-data', here is the error: "Multipart: Boundary not found"

Otherwise, "file" is undefined in the controller

Here is the controller:

@ApiConsumes('multipart/form-data')
  @ApiFile('file')
  @UseInterceptors(
    FileInterceptor('file', multerOptions([MimeExtEnum.XLS, MimeExtEnum.XLSX])),
  )
  @Post('/uploadFile')
  public async uploadFile(
    @UploadedFile() file,
  ): Promise<any> {
      console.log("file", file); //here the file is undefined
  }

Upvotes: 1

Views: 1200

Answers (1)

Maxim Orlov
Maxim Orlov

Reputation: 2582

When you're sending a form with fetch in the frontend, don't set Content-Type header yourself. If you do, it won't have the form boundary and the multipart/form-data request will be parsed incorrectly in the backend.

You can omit the header because the browser will set it for you, which includes a unique boundary.

  • Your header: Content-Type=multipart/form-data;
  • Browser's header: Content-Type=multipart/form-data; boundary=------WebKitFormBoundaryg7okV37G7Gfll2hf--

Second, to send a file you need to construct a form first using FormData API, append the file to it, and then send the form to the backend.

Here's how it looks:

// Construct a form and append the file to it
const form = new FormData();
form.append('file', file);

// Send multipart/form-data request with fetch
// Note: don't set `Content-Type` header manually, the browser does this for you
fetch(`${path}`, {
  method: 'POST',
  body: form,
}).then((response) => {
  return response.status;
});

Upvotes: 2

Related Questions