Home > Blockchain >  Angular 13 NestJS File Upload
Angular 13 NestJS File Upload

Time:08-24

I have the following API in my NestJS controller:

import 'multer';
import csv from 'csvtojson';

import { Body, Controller, HttpStatus, Post, Res, UploadedFile, UseInterceptors } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { Express, Response } from 'express';

@Controller()
export class TestController {
  @Post('/test-upload')
  @UseInterceptors(FileInterceptor('file'))
  async bulkUpload(@UploadedFile() file: Express.Multer.File, @Body() body: any, @Res() response: Response) {
    try {
      const csvString = file.buffer.toString();
      const jsonArray = await csv().fromString(csvString);
      const id = body['id'];

      console.log(id);

      // Send back the results
      response.status(HttpStatus.OK).send(jsonArray);
    } catch (e) {
      response.status(HttpStatus.INTERNAL_SERVER_ERROR).send(e.message);
    }
  }
}

In my Angular code, I call it like this:

bulkUpload(event: any): Observable<any> {
  const url = '/test-upload';

  const formData = new FormData();
  formData.append('file', event.target.files[0]);
  formData.append('id', 4);

  const options = { reportProgress: true, responseType: 'json' };

  this.http.post<any>(url, formData, options).subscribe({
    next: (data: any) => console.log(data),
    error: (error: any) => console.log(error)
  });
}

I'm uploading the following CSV file:

id,name,status
2,test,active
5,foo,inactive
9,bar,inactive

and this is what the file looks like when I console log it on the Angular side:

lastModified: 1660946990280
lastModifiedDate: Fri Aug 19 2022 18:09:50 GMT-0400 (Eastern Daylight Time) {}
name: "test.csv"
size: 61
type: "text/csv"
webkitRelativePath: ""

When I call the bulkUpload function, I get the following error:

error: "Bad Request"
message: "Unexpected token - in JSON at position 0"
statusCode: 400

Does anyone know what I'm doing wrong? When I call the endpoint from Postman, it works fine and I get no errors. Am I missing some headers or something else? How do I upload a non-json file?

CodePudding user response:

I had to make sure the 'Content-Type' header was set to 'multipart/form-data'. I changed the Angular function to the following:

bulkUpload(event: any): Observable<any> {
  const url = '/test-upload';

  const formData = new FormData();
  formData.append('file', event.target.files[0]);
  formData.append('id', 4);

  let headers = new HttpHeaders();
  headers = headers.append('Content-Type', 'multipart/form-data');
  headers = headers.append('Accept', '*/*');

  this.http.post<any>(url, formData, { headers }).subscribe({
    next: (data: any) => console.log(data),
    error: (error: any) => console.log(error)
  });
}

After that, the error went away and I was able to send the file to my NestJS API correctly.

  • Related