Uploading Files and Serve Directory Listing Using NodeJS

Let’s explore on what options available for us.

Serving Uploaded FilesExpress provides us with some built-in middlewares and one express.

static middleware function.

Use the middleware as such:app.


static('public'));and put this below your other middleware functions.

Now when you run the app, you can serve the files in your public folder http://localhost:3000/uploads/file-1550484364038.

pngSo once you store the file location of the uploaded files on the database, you can then retrieve this information and provide it to the user as a static file.

However what if we want to show the directory listing of the public folder?.We can use another middleware module serve-index .

Let’s first install the module$ npm i serve-indexand then:const serveIndex = require('serve-index');//app.



use('/ftp', express.

static('public'), serveIndex('public', {'icons': true}));We commented the previous express.

static usage and replaced it with using the serve-index middleware.

What it essentially does is to serve the page containing directory listing for public when /ftp is requested.

Rerun the app and navigate to http://localhost:3000/ftp/You will be greeted with the following:Public FolderPublic/UploadsThis is exactly what we have in our public folder that we are serving.

Final index.

js fileOf course, you can use multer with any routers you may have.


post('/uploadURL', upload.

single('anynameyouwant'), .

Additionally you may also want to let users upload multiple files.

Then you just need to change upload.

single to upload.

array(‘name’, maxFileNumber)’ The files will the be populated under req.

files instead of req.

file For more information, check out the official documentation!If anyone finds these useful, feel free to share this or let me know should there be an error / bad practice / implementations.

Have fun coding!.

. More details

Leave a Reply