NodeJS – GridFS APIs Upload/Download Files to MongoDB – Mongoose

In the tutorial, we show you how to build a NodeJS web-application that uses stream-based GridFS APIs with Mongoose to upload/download files to MongoDB.

Related posts:
NodeJS – use Mongoose to save Files/Images to MongoDB
Crud RestAPIs with NodeJS/Express, MongoDB using Mongoose

NodeJS MongoDB GridFS

The MongoDB Node.js driver supports a stream-based API for GridFS, so we can .pipe() directly from file streams to MongoDB.

We create a web-application that uses GridFS APIs to upload/download files:

Upload File

Download File

Delete File

Meta Information

Practice

In the tutorial, we create a NodeJS project as below structure:

Setting up NodeJS project

-> Install Express, GridFS-Stream, Mongoose:

-> See package.json file:

Implement Server.js

Run & Check results

– Upload files:

  • localhost:8081/api/file/upload?filename=jsa_about.txt
  • localhost:8081/api/file/upload?filename=jsa_vision.png
  • localhost:8081/api/file/upload?filename=jsa_cover.png

-> Check MongoDB GridFS:

– Download File request: http://localhost:8081/api/file/download?filename=jsa_cover.png

NodeJS-GridFS-MongoDB-Upload-Download-File-download-request

– Get meta information of files: http://localhost:8081/api/file/meta?filename=jsa_cover.png

NodeJS-GridFS-MongoDB-Upload-Download-File-meta-info

– Delete a file request: http://localhost:8081/api/file/delete?filename=jsa_cover.png

-> Then check MongoDB after the deletion:

Sourcecode

To run below sourcecode, follow the guides:


step 0: download & extract zip file -> we have a folder ‘NodeJS-GridFS-MongDB’
step 1: cd NodeJS-GridFS-MongDB
step 2: npm install express gridfs-stream mongoose –save
step 3: node server.js

-> Sourcecode:

NodeJS-GridFS-MongDB

By grokonez | May 24, 2018.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*