Nestjs how to upload files specific folder.
xxxxxxxxxx
import {
Controller,
Post,
UseInterceptors,
UploadedFile,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { v4 as uuidv4 } from 'uuid';
@Post()
@UseInterceptors(
FileInterceptor('file', {
storage: diskStorage({
destination: './files',
filename: (req, file, cb) => {
const fileNameSplit = file.originalname.split('.');
const fileExt = fileNameSplit[fileNameSplit.length - 1];
cb(null, `${uuidv4()}.${fileExt}`);
},
}),
}),
)
async create(
@Body() body: any,
@UploadedFile() file: Express.Multer.File,
) {
body.imagen = file.filename;
return await this.createPostService.create(body);
}
Upload files to a specific path.
xxxxxxxxxx
Copy and paste this decorator into the controller.
Check that the files directory has been created.
@UseInterceptors(
FileInterceptor('file', {
storage: diskStorage({
destination: './files',
filename: (req, file, cb) => {
const fileNameSplit = file.originalname.split('.');
const fileExt = fileNameSplit[fileNameSplit.length - 1];
cb(null, `${Date.now()}.${fileExt}`);
},
}),
}),
)
@Post("/upload")
create(
@UploadedFile() file: Express.Multer.File,
) {
console.log(file)
}
nestjs upload single file
xxxxxxxxxx
@Post('upload')
@UseInterceptors(FileInterceptor('file'))
uploadFile(@UploadedFile() file: Express.Multer.File) {
console.log(file);
}