express文件上传
安装express,创建项目,添加sqlite3模块
express --sessions --css stylus --ejs myhotel
npm install sqlite3
node app #运行方式
源代码如下:
网站入口app.js
var express = require('express'); var routes = require('./routes'); var photo = require('./routes/photo'); var http = require('http'); var path = require('path'); var app = express(); // all environments app.set('port', process.env.PORT || 80); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.bodyParser({ keepExtensions: true, uploadDir: __dirname + '/uploads' } )); app.use(express.methodOverride()); app.use(express.cookieParser('your secret here')); app.use(express.session()); app.use(app.router); app.use(require('stylus').middleware(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } app.get('/', routes.index); app.post('/upload', photo.upload); app.get('/list', photo.list); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
connect.bodyParser()会有报错,替换如下
var multipart = require('connect-multiparty');
app.use(express.urlencoded()); // Replace for depricated connect.bodyParser() app.use(express.json()); // Replace for depricated connect.bodyParser() app.use(multipart({ uploadDir: __dirname + '/uploads' })) // Replace for depricated connect.bodyParser()
控制与路由
routes/index.js
exports.index = function(req, res){ res.render('index', { title: 'Express' }); };
routes/photo.js
var sqlite3 = require("sqlite3"), fs = require("fs"); var db = new sqlite3.Database("photos.db"); /* * GET users listing. */ exports.list = function(req, res){ var photos = []; db.serialize(function() { db.each("SELECT name, path FROM photos", function(err, row) { photos.push({name: row.name, path:row.path}) }, function(){ res.render("photos",{photos:photos}) }); }); }; exports.upload = function(req, res){ var name = req.param('name', null); fs.readFile(req.files.image.path, function (err, data) { // ... if(err) {throw err;} var hash = require('crypto').createHash('md5'); var target_path = 'images/uploads/' + hash.update(data+"").digest('hex') + "." + req.files.image.name.split(".")[1]; fs.writeFile("./public/"+ target_path, data, function (err) { if(err) {throw err;} db.serialize(function() { var stmt = db.prepare("INSERT INTO photos VALUES (?,?)"); stmt.run(name,target_path); stmt.finalize(); res.redirect("/list"); }); // db.close(); }); }); };
视图代码
view/index.ejs
<!DOCTYPE html> <html> <head></head> <body> <form enctype="multipart/form-data" action="/upload" method="POST"> <input type="text" id="name" name="name"></input> Send this file: <input name="image" id="image" type="file" /> <input name="tt" type="submit" value="Send File" /> </form> </body> </html>
view/photos.ejs
<!DOCTYPE html> <html> <head> <title>AB</title> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> <ul class="nostyle"> <% photos.forEach(function(photo){ %> <li><%= photo.name %> <img src="<%= photo.path %>" /></li> <% }) %> </ul> </body> </html>
样式控制public/stylesheets/style.styl
body padding: 50px font: 14px "Lucida Grande", Helvetica, Arial, sans-serif a color: #00B7FF .nostyle list-style-type: circle