NodeJS的Express框架构建web运用
Express4.0之后很对中间件都从Express中独立出来了。
例如原有的body-parser中间件(控制各种req,res以及可以负责文件的上传操作)
现在从Express中独立出来需要在app.js中单独加入
var bodyParser = require('body-parser');
还有session之类的在这里不一一举例。
直接来一个小功能熟悉一下Express&EJS
本文章介绍的都是基于Express4.0之后的(文件上传功能)
1.构建web项目
express -e fileServer
2.在config.json中添加新的模块
formidable是新增加的一个中间件用于文件的上传处理
详细的可查看https://github.com/felixge/node-formidable
{
"name": "fileServer",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"express": "~4.2.0",
"static-favicon": "~1.0.0",
"morgan": "~1.0.0",
"cookie-parser": "~1.0.1",
"body-parser": "~1.0.0",
"debug": "~0.7.4",
"ejs": "~0.8.5",
"formidable": "~1.0.0"
}
}
3.在app中添加文件上传的路由规则&文件上传的处理
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var formidable = require('formidable');
var fs = require('fs');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser({defer:true}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/users', users);
//此次为了方便直接写在app中的路由处理,一般都会写入一个特殊的routes文件。做路由
app.route('/upload').get(function (req, res, next){
res.render('index', { title: 'Express' });
});
app.route('/upload').post(function (req, res, next) {//设置文件的上传处理
var form = new formidable.IncomingForm();
//设置文件的上传路径
form.uploadDir = "./files";
form.keepExtensions = true;
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});<span style="white-space:pre"> </span>//写返回头信息
res.write('received upload:\n\n');
console.log("form.bytesReceived->");
console.log("size:%d byte",files.file.size);<span style="white-space:pre"> </span>//文件大小
console.log("fileName:" , files.file.name);<span style="white-space:pre"> </span>//文件原始名称
console.log("filePath:" , files.file.path);<span style="white-space:pre"> </span>//文件路径(这个是经过formidable重写的文件名称)
console.log("type:" , files.file.type);<span style="white-space:pre"> </span>//文件类型
console.log("lastModifiedDate:" , files.file.lastModifiedDate);
res.end();
});
});
var server = app.listen(8000, function() {
console.log('FileServer on port %d', server.address().port);
});
/// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
4.写映射的网页模版index.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1>Upload File</h1>
<form method='post' action='upload' enctype='multipart/form-data'>
<input type='file' name='file'/>
<input type='submit' value='submit'/>
</form>
</body>
</html>
在浏览器中输入localhost:8000/upload进行文件上传页面
后台控制台打印的上传数据