简体   繁体   English

Angular 13 + NestJS 文件上传

[英]Angular 13 + NestJS File Upload

I have the following API in my NestJS controller:我的 NestJS controller 中有以下 API:

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:在我的 Angular 代码中,我这样称呼它:

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:我正在上传以下 CSV 文件:

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:这就是当我在 Angular 端进行控制台登录时文件的样子:

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:当我调用bulkUpload function 时,我收到以下错误:

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.当我从 Postman 调用端点时,它工作正常并且我没有收到任何错误。 Am I missing some headers or something else?我是否缺少一些标题或其他内容? How do I upload a non-json file?如何上传非 json 文件?

I had to make sure the 'Content-Type' header was set to 'multipart/form-data'.我必须确保将“Content-Type”header 设置为“multipart/form-data”。 I changed the Angular function to the following:我将 Angular function 更改为以下内容:

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.之后,错误消失了,我能够正确地将文件发送到我的 NestJS API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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