1. How can a complete blog lack of images, there are currently three ways to upload files:
(1) The File upload function with Express comes with no database.
(2) Using formidable external module, no database involved.
(3) uploading to MongoDB, involving the database.
As can be seen, the first way is the simplest, express through Bodyparser () parse the request body, so we can use Bodyparser () to implement the file upload function.
2. Implementation process
2.1 First Open Header.ejs, in <li><a href= "/post" title= ' Publish ' > published </a></li>, add a line of code in front:
<li><a href= "/upload" title= "upload" > Upload </a></li>
2.2 Then, open index.js and add the following code after the App.get ('/logout ') function:
1 //upload File page routing2Router.get ('/upload ', checklogin);//restrict only users who are logged on to upload files3Router.get ('/upload ',function(req, res) {4Res.render (' Upload ', {5Title: ' File Upload ',6 User:req.session.user,7Success:req.flash (' Success '). ToString (),8Error:req.flash (' ERROR '). toString ()9 });Ten});
2.3 Second, we create a new Upload.ejs below the Views folder, adding the following code:
1<div class= ' container ' >234<form enctype= "Multipart/form-data" method= "post" action= "/upload" class= "Form-horizontal" >5<div class= "Form-group" >6<label for= "File1" > File input </label>7<input type= "File" name= "File1" >8</div>9<div class= "Form-group" >Ten<label for= "File1" > File input </label> One<input type= "File" name= "File1" > A</div> -<div class= "Form-group" > -<label for= "File1" > File input </label> the<input type= "File" name= "File1" > -</div> -<button type= "Submit" class= "btn btn-primary" > Uploads </button> -</form> +</div>
2.4 Then, modify app.js and add the following code:
1 varMulter = require (' Multer '));2 //File Upload plugin3 varStorage =Multer.diskstorage ({4Destinationfunction(req, file, CB) {5cbNULL, './public/images/user ')6 },7FileNamefunction(req, file, CB) {8cbNULL, File.fieldname + '-' +Date.now ())9 }Ten }); OneApp.use (Multer ({storage:storage}). any ());
2.5 Now we just have a form to upload the file, and we can't upload the file, then we add support for uploading the file. Add the following code after Router.get ('/upload '):
Router.post ('/upload ', Checklogin); Router.post (function (req, res) { Req.flash (' Success ', ' File upload succeeded! ' ); Res.redirect ('/upload ');});
At this point, we have added the file upload function to the blog.
A simple blog system (iii) to increase the file upload function