我正在尝试将文件上传到我的 Nest.js 服务器,但收到错误:
Error: Unsupported Media Type: multipart/form-data; boundary=--------------------------140603536005099484714904
我关注了这个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);
}
最佳答案
我假设您使用的是FastifyAdapter
而不是express。
在文档中它说:
Multer will not process any form which is not multipart (multipart/form-data). Besides, this package won't work with the FastifyAdapter.
所以如果可能的话,改用 express 。否则,您必须使用 Fastify-Multipart直到 Nest.js 原生支持它。
关于node.js - 使用 Fastify 和 Nestjs 上传文件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54291758/