使用Angular 6和Nestjs上传文件错误

时间:2019-01-21 14:11:19

标签: node.js angular typescript file-upload nestjs

我正在尝试将文件上传到我的nest.js服务器,但出现错误:

  

错误:不支持的媒体类型:multipart / form-data; boundary = -------------------------- 140603536005099484714904

Error File

我遵循了这个documentation

Angular 6代码

public async Upload<TReponse>(file: File, path) {
    try {

      const formData = new FormData();
      formData.append("file", file);

      //>> function to upload and applying header as null

      const result = await this.http.post(this.baseUrl + path, formData, { headers: null }).pipe(map((response: any) => response)).toPromise();
      var response = result as ApiResponseObject<TReponse>;

      return response;
    }
    catch (ex) {
      var result = new ApiResponseObject<TReponse>()
      result.message = ex.message;
      result.isSuccess = false;

      return result;
    }
    finally {
    }
 }

NestJs代码模块代码

import { Module, NestModule, MiddlewareConsumer, MulterModule } from '@nestjs/common';
import { UserService } from './services/user.service';
import { UserController } from './user.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './dto/user.entity';
import * as multer from 'multer';

@Module({
    imports: [TypeOrmModule.forFeature([User]),
    MulterModule.register({
        dest: '/public',
        fileFilter: (req, file, cb) => {
            let extension = (file.originalname.split('.').pop())
            //Put here your custom validation for file extensións.
            // To accept the file pass `true`, like so:
            cb(null, true);
            // To reject this file pass `false` or throw Exception, like so:
            //cb(new HttpException ("File format is not valid", HttpStatus.BAD_REQUEST), false)
        },
        limits: {
            fileSize: 2097152 //2 Megabytes
        },
        storage: multer.diskStorage({
            destination(req, file, cb) {
                cb(null, './public');
            },
            filename(req, file, cb) {
                cb(null, "usman_" + file.originalname);
            },
        })
    }),
    ],
    providers: [UserService],
    controllers: [UserController],
})

NestJs代码组件代码

@Post("upload")
@UseInterceptors(FileInterceptor('file'))
async upload(@UploadedFile() file, @Request() req) {
    console.log(file);
    console.log(req.files);
}

1 个答案:

答案 0 :(得分:0)

我假设您使用的是FastifyAdapter而不是express。 在文档中说:

  

Multer将不处理任何非多部分形式   (多部分/表单数据)。 此外,该软件包不适用于   FastifyAdapter。

因此,如果可能,请切换到快递。否则,您必须使用Fastify-Multipart直到nest.js本身支持。