简体   繁体   中英

Angular 13 + NestJS File Upload

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM