如何在“控制器”页面中将人体数据恢复到FileInterceptor中

时间:2019-11-26 08:15:27

标签: angular typescript controller upload nestjs

我想将表单中的数据恢复到控制器的FileInterceptor部分中。

我上传了文件。我使用表格发送它,并且我还发送了一个文件夹名称,这用于知道我要存储在哪里。

我的问题是:我在FileInterceptor函数中找不到文件夹名称,该文件夹位于@body内。

我也尝试将文件夹名称放入file参数中,但是存在只读错误。

有我的代码:

前端:

upload.component.ts

 onSubmit() {
    const formData = new FormData()
    formData.append('file', this.form.get('file').value);
    formData.append('folder', this.form.get('folder').value);
    this.uploadService.upload(formData).subscribe(
      (res) => this.uploadResponse = res,
      (err) => this.error = err
    );
  }

upload.service.ts

export class UploadService {

  SERVER_URL: string = "http://localhost:3000";

  constructor(private httpClient: HttpClient) {
  }

  public upload(data) {
    let uploadURL = `${this.SERVER_URL}/upload/file`;

    return this.httpClient.post<any>(uploadURL, data, {
      reportProgress: true,
      observe: 'events'
    }).pipe(map((event) => {

        switch (event.type) {

          case HttpEventType.UploadProgress:
            const progress = Math.round(100 * event.loaded / event.total);
            return { status: 'progress', message: progress };

          case HttpEventType.Response:
            return event.body;
            default:
              return `Unhandled event: ${event.type}`;
        }
      })
    );
  }
}

在我的后端:

upload.controller.ts

@Controller('upload')
export class UploadController {

    constructor(private readonly UploadService: UploadService) {

    }

    @Post('file')

    @UseInterceptors(FileInterceptor('file',
        {

                storage: diskStorage({
                    destination: (req: any, file: any, cb: any) => {
                        console.log('--------------------------------------------------------');
                        //console.log(req.body);
                        console.log('--------------------------------------------------------');
                        console.log(file);
                        console.log('--------------------------------------------------------');
                        console.log(cb);
                        cb(null,'./uploadedFiles/');
                    },
                filename: (req, file, cb) => {
                    return cb(null, `${file.originalname}${extname(file.originalname)}`)
                }
            })
        }
    )
    )
      async serveFile(@Param('fileName') fileName, @Body() resBody, @Res() res): Promise<any> {
        console.log(resBody.folder);
      }

我想整理一下resBody.folder中的内容,放在cb(null,'./uploadedFiles/');之后 具有类似cb(null,'./uploadedFiles/{resBody.folder}');

我在控制台中看到的内容:

--------------------------------------------------------
{ fieldname: 'file',
  originalname: 'test.txt',
  encoding: '7bit',
  mimetype: 'text/plain' }
--------------------------------------------------------
[Function]
Contrat

这就是我在F12网络中看到的Form Data内容:

Form Data
  file: (binary)
  folder: Contrat

预先感谢您的帮助!

0 个答案:

没有答案