The third chapter of the original tutorial Https://github.com/nswbmw/N-blog/wiki/_pages
There are currently three ways to upload a file:
Use Express's own file upload feature, no database involved
Use formidable external module, no database involved
Uploading to MongoDB, involving the database
Here the first type, the user will be stored on the file in: blog/public/images/directory.
Blog/views/header.ejs add a line before <span><a title= "publish" href= "/post" >post</a</span>:
<span><a title= "Upload" href= "/upload" >upload</a</span>
Index.js Add code:
Fs=require (' FS '),
And:
<span style= "White-space:pre" ></span>app.get ('/upload ', checklogin); App.get ('/upload ', function (req, RES) {res.render (' upload ', {title: ' File Upload ', User:req.session.user,success:req.flash (' success '). ToString (), Error: Req.flash (' Error '). toString ()}); App.post ('/upload ', checklogin); App.post ('/upload ', function (req,res) {for (var i in req.files) {if (req.files[i].size= =0) {//Use synchronous mode to delete a file Fs.unlinksync (Req.files[i].path); Console.log ("Successfully removed an empty file");} Else{var target_path= './blog/public/images/' +req.files[i].name;//rename a file by using synchronous mode Fs.renamesync (Req.files[i].path, Target_path); Console.log (' Successfully rename a file ');}} Req.flash (' Success ', ' File upload succeeded '); Res.redirect ('/upload ');});
New Upload.ejs under blog/views/:
<%-include header%><form method= ' post ' action= '/upload ' enctype= ' multipart/form-data ' > <input Type= "File" Name= "file1" multiple= "multiple"/><br> <input type= "file" Name= "File2" multiple= " Multiple "/><br> <input type=" file "Name=" File3 "multiple=" multiple "/><br> <input Type= "File" Name= "file4" multiple= "multiple"/><br> <input type= "file" Name= "File5" multiple= " Multiple "/><br> <input type=" submit "/></form><%-include footer%>
Blog/app.js App.use (Express.bodyparser ()); instead:
Keep the suffix name of the uploaded file and set the upload directory to/public/images app.use (Express.bodyparser ({keepextensions:true, Uploaddir: './blog/public/ Images '});
At this point we upload a picture: 123.png
Submit:
Post a blog and cite photos in your blog:
Published:
node. JS Blog Instance (iii) Add File Upload function