Upload And Download File In Node

Introduction

 
In this blog post, we will use multer middleware to upload a file. The template engine we will use is ejs.
 
If you aren't familiar with these resources, click the links below to learn about them,
Project Structure 
 
|------------------- app.js
|
|------------------- Views
|                             |--------- home.ejs 
|
|------------------- package.json 
 
 

Setup The Project Folder

1. Create a new folder using a console/terminal.
2. Open console/terminal, type mkdir followed by the folder name that you want to give.
3. Change to that folder by typing cd 'folder name'.
 
 
 

Setup Node For The Project

 
1. Now type npm init on your console/terminal. 
 
 
 
2. The npm init will create a package.json file.
3. We can create it manually as well. Just open the folder, add a new file, and name it package.json
4. It can be structured the same way as structured when using npm init.
 
The package.json will look like this:
 
 
 
5. Now we will install packages for our project using npm install, followed by the package names we want to install.
6. The following packages will be installed: express ejs body-parser multer mongoose.
 
 
7. This generates a folder name, node_modules, which will contain all the node packages.
8. After package installation, the package.json will look like this:
 
 
 
9. Now add a new file and name it app.js.
10. Go back to package.json file, and in scripts write start: app.js. This will be the application entry point.
 
 
11. Create the following new folders: 1.) views and 2.) public.
12. In view, add a file: home.ejs.
13. Here, we use .ejs extension for views file, since the template engine we are using is ejs. (click the following link to learn about ejs.)
14. Now in the public folder, make a new folder named uploads.
15. The uploaded files will be stored in the uploads folder.
 
 
 
app.js
  1. var express = require('express');  
  2. var bodyParser = require('body-parser');  
  3. var multer = require('multer');  
  4. var mongoose = require('mongoose');  
  5. var path = require('path');  
  6.   
  7. var app = express();  
  8.   
  9. var storage = multer.diskStorage({  
  10.     destination:function(req,file,cb){  
  11.          cb(null,'./public/uploads')  
  12.     },  
  13.     filename(req,file,cb){  
  14.         cb(null,file.originalname)  
  15.     }  
  16. })  
  17.   
  18. var upload = multer({storage:storage});  
  19.   
  20.  mongoose.connect('mongodb://localhost:27017/pics',{useNewUrlParser:false})  
  21.  .then(()=>console.log('connect')).catch(err=>console.log(err))  
  22.   
  23. // making the collection(table) schema  
  24. // it contains picspath file for saving the file path  
  25. var picSchema = new mongoose.Schema({  
  26.     picspath:String  
  27. })  
  28.   
  29. //collection schema will be saved in DB by name picsdemo   
  30. // picModel contains the instance of picdemo by which it can manipulate data in it.  
  31.  var picModel = mongoose.model('picsdemo',picSchema)  
  32.   
  33.   
  34. app.set('view engine','ejs');  
  35.   
  36. app.set("views",path.resolve(__dirname,'views'));  
  37.   
  38. var picPath = path.resolve(__dirname,'public');  
  39.   
  40. app.use(express.static(picPath));  
  41.   
  42. app.use(bodyParser.urlencoded({extended:false}))  
  43.   
  44. app.get('/',(req,res)=>{  
  45.     picModel.find((err,data)=>{  
  46.              if(err){  
  47.                  console.log(err)  
  48.              }  
  49.             if(data){  
  50.                 console.log(data)  
  51.                 res.render('home',{data:data})  
  52.             }   
  53.            else{  
  54.                res.render('home',{data:{}})  
  55.            }   
  56.     })        
  57. })  
  58.   
  59. app.post('/',upload.single('pic'),(req,res)=>{  
  60.     var x= 'uploads/'+req.file.originalname;  
  61.     var picss = new picModel({  
  62.         picspath:x  
  63.     })  
  64.     picss.save((err,data)=>{  
  65.          if(err){  
  66.              console.log(err)  
  67.          }  
  68.          else{  
  69.              console.log('data',data)  
  70.             res.redirect('/')  
  71.          }  
  72.     })  
  73. })  
  74.   
  75. app.get('/download/:id',(req,res)=>{  
  76.      picModel.find({_id:req.params.id},(err,data)=>{  
  77.          if(err){  
  78.              console.log(err)  
  79.          }   
  80.          else{  
  81.             var path= __dirname+'/public/'+data[0].picspath;  
  82.             res.download(path);  
  83.          }  
  84.      })  
  85. })  
  86.   
  87. const port = process.env.PORT || 3000 ;  
  88. app.listen(port,()=>console.log(`server running at ${port}`))  
  89.   
  90. module.exports = app;  
  • mongoose.connect() - Will setup the connection with local db on our system.
  • localhost:27017/pics - Pics is the name of our database which will be created on the server when we insert data into it.
  • app.set("views",path.resolve(__dirname,"views")) - This tells express where the views folder is.
  • app.set("view engine","ejs") - This tells express that any file ending in .ejs should be rendered with ejs packages.
  • express.static() - To serve static files such as images, CSS files, and JavaScript files. This uses the middleware function.
  • bodyParser - For fetching form data from the coming request.
  • mongoose.Schema({}) - Contains the fields of our collection(table).
  • mongoose.model() - Contains collection(table) name and the object containing collection(table) field data.
  • upload.single('pic') - With this, we need to provide the same name as the name attribute which we used to upload the file.pic. It is the same name which is given in the name attribute. <input type="file"name="pic">.

Views

 
home.ejs 
  1. <html lang="en">  
  2. <head>  
  3.     <meta charset="UTF-8">  
  4.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  5.     <meta http-equiv="X-UA-Compatible" content="ie=edge">  
  6.     <title>Document</title>  
  7. </head>  
  8. <body>  
  9.     <h2>Upload Files</h2>  
  10.        <form action="/" method="POST" enctype="multipart/form-data">  
  11.         <input type="file" name="pic"><br>  
  12.         <input type="submit" value="Upload">  
  13.        </form><br><br><br><br>  
  14.    <h2>Download Files</h2>  
  15.        <table>  
  16.            <thead>  
  17.                <tr>  
  18.                    <td>  
  19.                        image  
  20.                    </td>  
  21.                    <td>  
  22.                        download  
  23.                    </td>  
  24.                </tr>  
  25.            </thead>  
  26.            <tbody>  
  27.                <% for(var i=0; i < data.length > 0; i++) {%>  
  28.                 <tr>  
  29.                     <td><img src="<%= data[i].picspath %>" style="width:100px; height:100px;"></td>  
  30.                     <td>  
  31.                         <form action="/download/<%= data[i]._id %>" method="GET">  
  32.                          <input type="submit" value="Download">  
  33.                        </form>  
  34.                     </td>  
  35.                 </tr>  
  36.                <% } %>  
  37.            </tbody>  
  38.        </table>  
  39. </body>  
  40. </html>  

Summary

 
In the above blog, we learned about how to upload and download files in Node.