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
- var express = require('express');
- var bodyParser = require('body-parser');
- var multer = require('multer');
- var mongoose = require('mongoose');
- var path = require('path');
-
- var app = express();
-
- var storage = multer.diskStorage({
- destination:function(req,file,cb){
- cb(null,'./public/uploads')
- },
- filename(req,file,cb){
- cb(null,file.originalname)
- }
- })
-
- var upload = multer({storage:storage});
-
- mongoose.connect('mongodb://localhost:27017/pics',{useNewUrlParser:false})
- .then(()=>console.log('connect')).catch(err=>console.log(err))
-
-
-
- var picSchema = new mongoose.Schema({
- picspath:String
- })
-
-
-
- var picModel = mongoose.model('picsdemo',picSchema)
-
-
- app.set('view engine','ejs');
-
- app.set("views",path.resolve(__dirname,'views'));
-
- var picPath = path.resolve(__dirname,'public');
-
- app.use(express.static(picPath));
-
- app.use(bodyParser.urlencoded({extended:false}))
-
- app.get('/',(req,res)=>{
- picModel.find((err,data)=>{
- if(err){
- console.log(err)
- }
- if(data){
- console.log(data)
- res.render('home',{data:data})
- }
- else{
- res.render('home',{data:{}})
- }
- })
- })
-
- app.post('/',upload.single('pic'),(req,res)=>{
- var x= 'uploads/'+req.file.originalname;
- var picss = new picModel({
- picspath:x
- })
- picss.save((err,data)=>{
- if(err){
- console.log(err)
- }
- else{
- console.log('data',data)
- res.redirect('/')
- }
- })
- })
-
- app.get('/download/:id',(req,res)=>{
- picModel.find({_id:req.params.id},(err,data)=>{
- if(err){
- console.log(err)
- }
- else{
- var path= __dirname+'/public/'+data[0].picspath;
- res.download(path);
- }
- })
- })
-
- const port = process.env.PORT || 3000 ;
- app.listen(port,()=>console.log(`server running at ${port}`))
-
- 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
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>Document</title>
- </head>
- <body>
- <h2>Upload Files</h2>
- <form action="/" method="POST" enctype="multipart/form-data">
- <input type="file" name="pic"><br>
- <input type="submit" value="Upload">
- </form><br><br><br><br>
- <h2>Download Files</h2>
- <table>
- <thead>
- <tr>
- <td>
- image
- </td>
- <td>
- download
- </td>
- </tr>
- </thead>
- <tbody>
- <% for(var i=0; i < data.length > 0; i++) {%>
- <tr>
- <td><img src="<%= data[i].picspath %>" style="width:100px; height:100px;"></td>
- <td>
- <form action="/download/<%= data[i]._id %>" method="GET">
- <input type="submit" value="Download">
- </form>
- </td>
- </tr>
- <% } %>
- </tbody>
- </table>
- </body>
- </html>
Summary
In the above blog, we learned about how to upload and download files in Node.