Def*_*ine 6 rest file-upload multer nestjs
我尝试使用 NEST.JS 和 MULTER 制作一个简单的文件上传 REST 接口 - 但它不起作用。我能够将二进制文件debug.log发布到 URL,并且看到“Hello undefined”消息,但上传的文件既不是在给定文件夹上传中创建的,也不是因为扩展名不正确而被拒绝 - 根据文件过滤器。但是,没有显示任何异常或错误。
为什么 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, file, 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, callback) {
callback(null, 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);
}
}
Run Code Online (Sandbox Code Playgroud)
我知道对于提出这个问题的人来说这是一个迟到的答复,但答案是为了将来面临这个问题的人。
首先查看nestjs文档
如果MulterModule在文件中注册,*.module.ts它将在文件夹外部创建上传目录src。这是一个很好的做法。
MulterModule.register({
dest: './upload',
});
Run Code Online (Sandbox Code Playgroud)
如果需要更改目标目录,请使用destination: String|callbackfromDiskStorageOptions或dest:stringfrom FileInterceptor。对于上传路径,请使用src/../upload将文件夹保留在src目录之外的方法。
问题中提到的上述代码的其他问题:
console.log("Hello " + file);这里文件的原因是Object并尝试与String.
将其更改为console.log("Hello ", file);
扩展名不正确,未显示异常或错误
fileFilter: function (req, file, 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);
}
Run Code Online (Sandbox Code Playgroud)
这里需要添加一个return.
| 归档时间: |
|
| 查看次数: |
6464 次 |
| 最近记录: |