NestJS: Type-safe File Uploads #161
Replies: 7 comments 4 replies
-
I've been struggling to make some NestJS things work for long time. Getting good examples about specific topics was hard, until I found your posts. Thank you very much for the clear and detailed explanations! |
Beta Was this translation helpful? Give feedback.
-
Thanks very much for your blog, I gain a clear understanding of how NestJS file upload and OpenAPI work together. A quick question, when using FileFieldsInterceptor, how can I access individual items within files. In FilesInterceptors, I can loop throught files async uploadMultipleFiles(
@UploadedFiles() files: Array<Express.Multer.File>,
) {
const response = [];
files.forEach((file) => {
const fileReponse = {
originalname: file.originalname,
newfilename: file.filename,
};
response.push(fileReponse);
});
return response;
} The same code would generate this error in FileFieldsInterceptor [Nest] 24176 - 11/23/2021, 8:27:32 PM ERROR [ExceptionsHandler] files is not iterable I have to do this to make FileFieldsInterceptor works for me @Post('uploadFields')
@ApiConsumes('multipart/form-data')
@UseInterceptors(
FileFieldsInterceptor(
[
// 👈 multiple files with different field names
{ name: 'avatar', maxCount: 1 },
{ name: 'background', maxCount: 1 },
],
{
storage: diskStorage({
destination: getFileUploadFolder,
filename: randomizedFileName,
}),
fileFilter: imageFileFilter,
},
),
)
@ApiBody({
schema: {
type: 'object',
properties: {
// 👈 matches field names
avatar: {
type: 'string',
format: 'binary',
},
background: {
type: 'string',
format: 'binary',
},
},
},
})
async uploadFields(
@UploadedFiles()
files: {
avatar?: Express.Multer.File[];
background?: Express.Multer.File[];
},
) {
const response = [];
files.avatar.forEach((file) => {
const fileReponse = {
originalname: file.originalname,
newfilename: file.filename,
};
response.push(fileReponse);
});
files.background.forEach((file) => {
const fileReponse = {
originalname: file.originalname,
newfilename: file.filename,
};
response.push(fileReponse);
});
return response;
} TIA |
Beta Was this translation helpful? Give feedback.
-
Thank you very much for this good example.
|
Beta Was this translation helpful? Give feedback.
-
Thank s a lot. Good example. Official documentation lacks such info. |
Beta Was this translation helpful? Give feedback.
-
Thank you for this blog. I have a question, is it possible to to extend ApiImageFile to ApiImageFiles? |
Beta Was this translation helpful? Give feedback.
-
How i can validate file size ? I can't get file size in fileFilter. |
Beta Was this translation helpful? Give feedback.
-
What if you got a dto and fileupload in the same endpoint? |
Beta Was this translation helpful? Give feedback.
-
NestJS: Type-safe File Uploads
Learn how to apply Swagger decorators for type-safe file upload endpoints.
https://notiz.dev/blog/type-safe-file-uploads
Beta Was this translation helpful? Give feedback.
All reactions