//我是用php的思想來學習nodejs
var express = require('express'); var router = express.Router(); var fs = require('fs'); var path= require("path"); var formidable = require('formidable'); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express+EJS+mysql+s2' }); }); router.post('/file-upload', function(req, res, next) { console.log('開始文件上傳....'); var form = new formidable.IncomingForm(); //設置編輯 form.encoding = 'utf-8'; //設置文件存儲路徑 form.uploadDir = "./public/images/"; //保留后綴 form.keepExtensions = true; //設置單文件大小限制 form.maxFieldsSize = 2 * 1024 * 1024; //form.maxFields = 1000; 設置所以文件的大小總和 form.parse(req, function(err, fields, files) { //console.log(fields); console.log(files.thumbnail.path); console.log('文件名:'+files.thumbnail.name); var t = (new Date()).getTime(); //生成隨機數 var ran = parseInt(Math.random() * 8999 +10000); //拿到擴展名 var extname = path.extname(files.thumbnail.name); //path.normalize('./path//upload/data/../file/./123.jpg'); 規范格式文件名 var oldpath = path.normalize(files.thumbnail.path); //新的路徑 let newfilename=t+ran+extname; var newpath = './public/images/'+newfilename; console.warn('oldpath:'+oldpath+' newpath:'+newpath); fs.rename(oldpath,newpath,function(err){ if(err){ console.error("改名失敗"+err); } res.render('index', { title: '文件上傳成功:', imginfo: newfilename }); }); //res.end(util.inspect({fields: fields, files: files})); }); }); /* supervisor ./bin/www */ module.exports = router;
<!DOCTYPE html> <html> <head> <title><%= title %></title> <link rel=’stylesheet’ href=’/stylesheets/style.css’ /> </head> <body> <h5>這里變量沒有輸出但沒有報銷:<%= locals.title %></h5> <p>Welcome to <%= title %></p> <img src='./images/<%= locals.imginfo %>' width='200'/> <form method="post" enctype="multipart/form-data" action="/file-upload"> <input type="text" name="username"> <input type="password" name="password"> <input type="file" name="thumbnail"> <input type="submit"> </form> </body> </html>