我尝试使用nesT.JS和MULTER制作一个简单的文件上传REST接口-但它不起作用。我可以将二进制文件 debug.log 发布到URL,并且看到“ Hello undefined”消息,但是在给定的文件夹 uploads 中都没有创建上传的文件>也不会因为扩展名不正确而被拒绝-根据文件过滤器。 但是,没有显示异常或错误。
为什么multer不起作用? 为什么 @Uploadedfile()文件显示为未定义?
谢谢
import { Controller,Post,Request,UseInterceptors,FileInterceptor,UploadedFile,HttpCode,HttpException,HttpStatus } from '@nestjs/common';
import { diskStorage,File } from 'multer';
const path = require('path');
const myStorage = diskStorage({
destination: function (req,file,callback) {
callback(null,'./uploads/');
},limits: { fileSize: 1000000 },fileFilter: function (req,cb) {
const extension = path.extname(file.originalname).toLowerCase()
const mimetyp = file.mimetype
if (extension !== '.jpg' || mimetyp !== 'image/jpg') {
cb(new HttpException('Only images are allowed',HttpStatus.NOT_accEPTABLE));
}
cb(null,true);
},filename: function (req,file.fieldname + '_' + Date.now() + '.jpg');
}
});
@Controller('documents')
export class DocumentsController {
@Post()
@HttpCode(HttpStatus.OK)
@UseInterceptors(FileInterceptor('file',{ storage: myStorage }))
public async addDocument(@UploadedFile() file): Promise<any> {
console.log("Hello " + file);
}
}