I initialize MutlerModule
to app.module
:
MulterModule.registerAsync({
imports: [ ConfigModule ],
inject: [ ConfigService ],
async useFactory(configService: ConfigService)
{
const uploadFolder = configService.get<IConfig[ "uploadFolder" ]>("uploadFolder");
return {
storage: diskStorage({
destination: uploadFolder,
filename(req, file, cb)
{
const filename = `${ Date.now() }-${ file.originalname }`;
cb(null, filename);
}
})
};
}
}),
In uploadFolder
we have uploads
. Further for some route I want to save not in uploads
but in uploads/category
, how can I do it without duplicating the code?
What I need to change somewhere that the files that are sent to this route go to uploads/category
@Controller("category")
export class CategoryController
{
@UseInterceptors(FileInterceptor("image"))
@Post()
async create(
@UploadedFile(
new ParseFilePipeBuilder()
.addFileTypeValidator({ fileType: ALLOWED_IMAGE_TYPES.join() })
.addMaxSizeValidator({ maxSize: MAX_FILE_SIZE_BYTES })
.build({
fileIsRequired: false,
errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY
})
)
image
)
{
console.log(image);
}
}
2
Answers
Yes, you can configure the code to store your files in the folder
uploads/category
, you need to specify that path configuration in yourapp.modules.ts
file, following is the sample code as you’ve just providedMulterModule
code in the question:Hope this helps!
Path Based Folder
You can decide which folder to upload by passing a function to
destination
parameter :
Using this you can apply check where to store files based upon the path you get request from user.
Re-usable Multer Config way
And if you want to handle this at controller level you can create a function to get multer configuration :
In your controller, pass the specific folder name to the factory function and use it with FileInterceptor.