一人行者 万人追随
nodejs express+ejs+formidable实现文件上传
刚才做例子的时候遇到不少的问题:
1.表单提交的时候enctype=”multipart/form-data”(当有文件的时候需要加这个属性)
想问使用body-parser模块解析获取的参数是发现无法解析,prase回调中才能获取参数,去掉enctype=”multipart/form-data”
就可以了,参考 multer模块
2.Error: maxFileSize exceeded, received 2109740 bytes of file data
文件默认大小为2M 设置错误:form.maxFieldsSize = 20 * 1024 * 1024;
正确设置文件大小:form.maxFileSize = 20 * 1024 * 1024;
3.传多件的时候 只传一个文件获取的为一个对象,多个文件的时候问一个数组
express+ejs+formidable +bootstrap
ejs文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/bootstrap/css/bootstrap.css">
<script type="text/javascript" src="/bootstrap/js/jquery.min.js"></script>
<script type="text/javascript" src="/bootstrap/js/bootstrap.js"></script>
<script type="text/javascript" src="/bootstrap/js/index.js"></script>
</head>
<body>
<nav class="navbar navbar-default">
<!-- We use the fluid option here to avoid overriding the fixed width of a normal container within the narrow content columns. -->
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-6" aria-expanded="true">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<div class="navbar-collapse collapse in" id="bs-example-navbar-collapse-6" aria-expanded="true">
<ul class="nav navbar-nav">
<li class="active"><a href="http://localhost:8888/">Home</a></li>
<li><a href="http://localhost:8888/file">上传</a></li>
<li><a href="#">Link</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div>
</nav>
<div class="row">
<% if(value==1) {for(var i=0;i < arr.length;i++){%>
<div class="aa col-xs-6 col-md-3">
<a href="#" class="thumbnail">
<img src="images/saber.jpg" alt="...">
</a>
<h3 style="text-align: center"><%=arr[i]%></h3>
</div>
<%}}%>
<%if(value==4){%>
<form action="http://localhost:8888/fileUpload" method="post" onsubmit="return submitFun(this)" class="form-horizontal col-xs-6 col-md-3 col-xs-offset-1 col-md-offset-1" enctype="multipart/form-data">
<div class="form-group">
<select class="form-control" name="url">
<%for(var j = 0;j <arr.length;j++){%>
<option value="<%=arr[j]%>"><%=arr[j]%></option>
<%}%>
</select>
</div>
<div class="form-group">
<label for="exampleInputFile">File input</label>
<input type="file" id="InputFile" name="InputFile" multiple="multiple"/>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Sign in</button>
</div>
</div>
</form>
<%}%>
</div>
<script>
//限制上传文件不能为空
function submitFun(aaa){
if(aaa.InputFile.value ==""){
alert("请上传文件")
return false
}
return true
}
</script>
</body>
</html>
app.js启动文件
var express = require("express");
var router = require("./routes/router");
var formidable = require("node-formidable")
var ejs = require("ejs");
var fs = require("fs");
var path = require("path");
//date format工具
var dateutil = require("dateutil")
var app = express();
//设置view 默认会读(views)
app.set("view engine","ejs");
//修改默认路径为view
app.set("views","view");
//设置静态资源读取路径()
app.use(express.static("./public"))
app.get("/",router.showIndex);
app.get("/picture",router.eranPicture)
app.get("/file",router.earnFile)
app.post("/fileUpload",function (req,res) {
if(req.url == "/favicon.ico") {
res.end();
return;
}
var form = new formidable.IncomingForm()
//文件保留后最美
form.keepExtensions = true;
//多文件上传
form.multiples=true;
//临时文件目录
form.uploadDir = "./public/baocun";
//设置上传文件的大小
form.maxFileSize = 20 * 1024 * 1024;
//设置参数的大小
//form.maxFieldsSize = 20 * 1024 * 1024;
var files = [];
form.on('file', function (filed, file) {
files.push([filed, file]);
})
console.log(form.maxFieldsSize);
form.parse(req, function(err, fields, files) {
if(err){
console.log(err);
}
console.log(fields);
console.log(files);
if(files.InputFile == undefined){
res.end();
return;
}
Date.prototype.format = dateutil.format;
console.log(files.InputFile instanceof Array);
if(files.InputFile instanceof Array) {
for (var cc = 0; cc < files.InputFile.length; cc++) {
var str = new Date().format('Y-m-d-h-s') + parseInt(Math.random() * 123213 + 1111) + path.extname(files.InputFile[cc].name);
console.log(str);
fs.rename(files.InputFile[cc].path, "./public/file/" + fields.url + "/" + str, function (err) {
if (err) console.log(err)
});
}
}else {
var str = new Date().format('Y-m-d-h-s') + parseInt(Math.random() * 123213 + 21111) + path.extname(files.InputFile.name);
console.log(str);
fs.rename(files.InputFile.path, "./public/file/" + fields.url + "/" + str, function (err) {
if (err) console.log(err)
});
}
router.showIndex(req,res);
});
})
app.listen(8888)
router.js model(处理业务)
var fs = require("fs");
var formidable = require("node-formidable")
exports.showIndex = function (req,res) {
if(req.url&&req.url == "/favicon.ico") {
res.end();
return;
}
var url = "./public/file/"
var arr = fs.readdirSync(url)
var data = {};
data.arr = arr;
data.value = 1
res.render("index",data);
res.end();
}
exports.eranPicture = function (req,res) {
if(req.url == "/favicon.ico") {
res.end();
return;
}
var url = "./public/file/" + req.query.url;
var arr = fs.readdirSync(url);
var data = {};
data.url = req.query.url
data.arr = arr;
data.value = 2;
res.send(data)
res.end();
}
exports.earnFile = function (req,res) {
if(req.url == "/favicon.ico") {
res.end();
return;
}
var url = "./public/file/"
var arr = fs.readdirSync(url)
var data = {};
data.url = req.query.url
data.arr = arr;
data.value = 4;
res.render("index",data);
res.end();
}
//代码gitHub地址:https://github.com/daiyoucheng/photo