1.index.ejs文件中构建表单并实现前端验证
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= title %></title>
<link rel="stylesheet" type="text/css" href="/stylesheets/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="/stylesheets/signin.css" />
</head>
<body>
<div id="container" class="container">
<% if (locals.success) { %>
<div id="alt_sucess" class="alert alert-success">
<%- success %>
</div>
<% } %>
<% if (locals.error) { %>
<div id="alt_warning" class="alert alert-warning">
<%= error %>
</div>
<% } %>
<form class="form-signin" role="form" method="post" enctype='multipart/form-data'>
<h2 class="form-signin-heading">上传文件</h2>
<input id="fulAvatar" name="fulAvatar" type="file" class="form-control" />
<br/>
<button id="btnSub" class="btn btn-lg btn-primary" type="submit">上 传</button>
</form>
</div>
</body>
</html>
<script src="/javascripts/jquery-1.11.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
String.prototype.format = function (args) {
var result = this;
if (arguments.length > 0) {
if (arguments.length == 1 && typeof (args) == "object") {
for (var key in args) {
if (args[key] != undefined) {
var reg = new RegExp("({" + key + "})", "g");
result = result.replace(reg, args[key]);
}
}
}
else {
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] != undefined) {
var reg = new RegExp("({)" + i + "(})", "g");
result = result.replace(reg, arguments[i]);
}
}
}
}
return result;
}
$(function(){
$('#btnSub').on('click',function(){
var fulAvatarVal = $('#fulAvatar').val(),
errorTip = '<div id="errorTip" class="alert alert-warning">{0}</div> ';
$("#errorTip,#alt_warning").remove();
if(fulAvatarVal.length == 0)
{
$("#container").prepend(errorTip.format('请选择要上传的文件'));
return false;
}
var extName = fulAvatarVal.substring(fulAvatarVal.lastIndexOf('.'),fulAvatarVal.length).toLowerCase();
if(extName != '.png' && extName != '.jpg'){
$("#container").prepend(errorTip.format('只支持png和jpg格式图片'));
return false;
}
return true;
})
});
</script>
2.实现index.js中上传逻辑
var express = require('express') router = express.Router(), formidable = require('formidable'), fs = require('fs'), TITLE = 'formidable上传示例', AVATAR_UPLOAD_FOLDER = '/avatar/' /* GET home page. */ router.get('/', function(req, res) { res.render('index', { title: TITLE }); }); router.post('/', function(req, res) { var form = new formidable.IncomingForm(); //创建上传表单 form.encoding = 'utf-8'; //设置编辑 form.uploadDir = 'public' + AVATAR_UPLOAD_FOLDER; //设置上传目录 form.keepExtensions = true; //保留后缀 form.maxFieldsSize = 2 * 1024 * 1024; //文件大小 form.parse(req, function(err, fields, files) { if (err) { res.locals.error = err; res.render('index', { title: TITLE }); return; } var extName = ''; //后缀名 switch (files.fulAvatar.type) { case 'image/pjpeg': extName = 'jpg'; break; case 'image/jpeg': extName = 'jpg'; break; case 'image/png': extName = 'png'; break; case 'image/x-png': extName = 'png'; break; } if(extName.length == 0){ res.locals.error = '只支持png和jpg格式图片'; res.render('index', { title: TITLE }); return; } var avatarName = Math.random() + '.' + extName; var newPath = form.uploadDir + avatarName; console.log(newPath); fs.renameSync(files.fulAvatar.path, newPath); //重命名 }); res.locals.success = '上传成功'; res.render('index', { title: TITLE }); }); module.exports = router;
注意:在public文件夹中创建avatar文件夹以供文件存放
http://www.cnblogs.com/zhongweiv/p/nodejs_express_formidable.html