- server.js
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}).array('image')); //此处'image'表示上传文件类型为图片类型,下面注解。
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.post('/file_upload', function (req, res) {
console.log(req.files[0]); // 上传的文件信息
var des_file = __dirname + "/" + req.files[0].originalname;
fs.readFile( req.files[0].path, function (err, data) {
fs.writeFile(des_file, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message:'File uploaded successfully',
filename:req.files[0].originalname
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("应用实例,访问地址为 http://%s:%s", host, port)
})
Mac终端下执行以上代码:
$ node server.js ,会报错:
Error: EACCES: permission denied, mkdir '/tmp'
提示没有读写权限;于是乎我抱着怀疑态度加了sudo执行$ sudo node server.js,可以成功运行了!上传文件后,在Mac硬盘根目录下生产了tmp临时文件!这就是报错的原因,
app.use(multer({ dest: '/tmp/'}).array('image'));
'/tmp',是在系统根目录下创建tmp;要改为'./tmp',才是在当前目录下创建tmp目录。
注解
multer.single(‘file’), //适用于单文件上传
multer.array(‘file’,num), //适用于多文件上传,num为最多上传个数,上传文件的数量可以小于num,
multer.fields(fields), //适用于混合上传,比如A类文件1个,B类文件2个。官方API有详细说明。
- 附index.htm代码:
<html>
<head>
<title>文件上传表单</title>
</head>
<body>
<h3>文件上传:</h3>
选择一个文件上传: <br />
<form action="/file_upload" method="post" enctype="multipart/form-data">
<input type="file" name="image" size="50" />
<br />
<input type="submit" value="上传文件" />
</form>
</body>
</html>
网友评论