方式一:
直接在FileInterceptor修改
引入依赖
import { Controller, Post, UseInterceptors ,UploadedFile} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import multer = require('multer');
file.controller.ts
@Post('upload')
@UseInterceptors(FileInterceptor('file', {
storage: multer.diskStorage({
destination: (req, file, cb) => {
cb(null, '/Users/xxxxx/Desktop/aaa');
},
filename: (req, file, cb) => {
cb(null, file.originalname);
},
}),
}))
async uploade(@UploadedFile() file) {
return file;
}
方式二
在Module添加,这种方式更友好,图片会存储在fileUpload目录下
file.module.ts
import { Module } from '@nestjs/common';
import { FileController } from './file.controller';
import { FileService } from './file.service';
import { MulterModule } from '@nestjs/platform-express';
import dayjs = require('dayjs');
import { diskStorage } from 'multer';
import * as nuid from 'nuid';
@Module({
imports:[
MulterModule.register({
storage: diskStorage({
//自定义路径
destination: `./fileUpload/${dayjs().format('YYYY-MM-DD')}`,
filename: (req, file, cb) => {
// 自定义文件名
// const filename = `${nuid.next()}.${file.mimetype.split('/')[1]}`;
// return cb(null, filename);
return cb(null, file.originalname);
},
}),
}),
],
controllers: [FileController],
providers: [FileService]
})
export class FileModule {}
file.controller.ts
@Post('upload')
@UseInterceptors(FileInterceptor('file'))
async UploadedFile(@UploadedFile() file) {
return file;
}