index.js
var express=require("express"); var app=express(); var router=require("./router") app.set("view engine","ejs"); // app.set("views"); app.use(express.static("./upload")); app.use(express.static("/public")); app.get("/",router.indexPage); app.get("/upload",router.upload); app.post("/postImg",router.postImg); app.get("/allPhoto",router.allPhoto) app.use(function (req,res) { console.log("404") res.render("404"); }); app.listen(3000);
router.js
var path=require("path"); var fs=require("fs"); var formidable=require("formidable"); var functions=require("./functions") exports.indexPage=function(req,res){ console.log("进入index.ejs....") res.render("index"); }; exports.upload=function (req,res) { res.render("upload") } exports.postImg=function (req,res) { var form=formidable.IncomingForm(); form.encoding='utf-8'; form.uploadDir='./upload'; form.keepExtensions=true; form.parse(req,function (err,fields,files,next) { console.log(files) if (err){ return; }; var size=parseInt(files.picture.size); console.log(size); if (size>1024*1024){ res.send("图片过大!") fs.unlink(files.picture.path); return; }; }) res.render("index"); } exports.allPhoto=function (req,res) { fs.readdir("./upload",function (err,files) { if (err){ res.send("未知找到相应资源") } var allPhoto=[]; files.forEach(function (photo,index) { console.log("index:.....is...."+index) fs.stat("./upload/"+photo,function (err,stats) { console.log(photo); if (stats.isFile()){ console.log("开始进行填充。。") allPhoto.push(photo) console.log("allPhoto.length...."+allPhoto.length) } if (index == files.length-1){ console.log(files.length-1) res.render("allPhoto",{ "allPhoto":allPhoto }); } }) }) }) }
新建文件夹 upload //存放上传的图片
新建文件夹 views //写ejs文件
indexPage.ejs
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>查看</h2> <a href="upload">上传图片</a> <a href="allPhoto">查看图片</a> </body> </html>
upload.ejs
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="postImg" method="post" enctype="multipart/form-data"> <label>请选择图片</label> <input type="file" name="picture" id="picture"><br> <input type="text" name="age"><br> <input type="submit" value="提交"> </form> </body> </html>
allPhoto.ejs
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>进入展示界面</h1> <%=allPhoto.length%> <%for(var i=0;i<allPhoto.length;i++){ %> <img src="<%=allPhoto[i]%>"/> <%}%> </body> </html>
404.ejs
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>404.....</h1> </body> </html>