NestJS File Uploading Using Multer GridFS
This guide will show you how you can implement file uploading into your NestJS application and the way to get back files from MongoDB. You will develop an application with five endpoints that will do the following:
- Upload an file;
- Upload multiple files;
- Get file info
- Get the file using mongo-gridfs.
- Delete file
This tutorial base on Nestjs File Storage With GridFS and Example of storing images with Mongoose and Nest.js #1169. Thank you for your kind contributions.
Let’s get started!
Setup
The first thing you need to install multer-gridfs-storage and @types/multer-gridfs-storage for uploading.
$ npm install -save multer-gridfs-storage @types/multer-gridfs-storage
Install mongo-gridfs for retrieve file info, download and delete query.
$ npm install -save github:khoapmd/mongo-gridfs
Uploading
Next, we need to create Multer configuration service to provide GridFS as storage option:
Now we can register MulterModule in our module definition using the configuration service class.
Don’t forget to add your FileModule from file.module.ts to your app.module.ts like this:
That is all we need to do for uploading files now we can use Multer decorators in our controller as usual Nestjs will take care of the rest.
You could also create “single upload “ by using FileInterceptor
and UploadedFile
, remember without an “s”.
Retrieve file info, download and delete query
Firstly, export FileInfoVm
model and named it file-info-vm.model.ts
You can inject the Mongoose Connection using the @InjectConnection()
decorator.
constructor(@InjectConnection() private readonly connection: Connection) {
this.fileModel = new MongoGridFS(this.connection.db, 'images');
}
Then, adding readStream
, findInfo
and deleteFile
, put them together in file.service.ts
Then creatfile-response-vm.model.ts
and export FileResponseVm
model
Finnally, here is the controller fully. Add the content below into header to get download the file include image files.
‘Content-Disposition’, ‘attachment; filename=’ + file.filename
Result
Conclusion
That’s all, I’ve just show you five endpoints that I told you in the beginning, now you can implement “uploading downloading, getting and deleting” api in your Nestj project.
Hope this help you.