基于express的文件上传
上传文件服务端
exports.postFile = function (req, res) {
var upfile = req.files.upfile;
var files = [];
if (upfile instanceof Array) {
files = upfile;
} else {
files.push(upfile);
}
for (var i = 0; i < files.length; i++) {
var file = files[i];
var path = file.path;
var name = file.name;
var target_path = "./upload/" + name;
fs.rename(path, target_path, function (err) {
if (err) throw err;
});
}
res.render('index', { title:'Complete' });
}
另外app.js加个app.use(express.bodyParser({uploadDir:'./upload_tmp'}));
页面前端
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="upfile" multiple/>
<input type="submit" value="upload">
</form>
9 回复
fs.rename(path, target_path, function (err) { if (err) throw err; });
提示fs没定义?
觉得那res.render 来得早了点,我会这样的,不过没试过:
fs.rename(path, target_path, function (err) {
if (err) throw err;
if (i == files.length)
res.render('index', { title:'Complete' });
});
嗯对文件操作不熟没引用
var fs = require('fs');
不过不知道为什么用上面的老不行我自己这样写了一个是可以的
fs.readFile(req.files.upfile.path, function(err, data){
var newPath = 'D:/node/test/20121210/upload/' + req.files.upfile.name;
fs.writeFile(newPath, data, function(err){
if(err)console.log(err);
else console.log("成功");
});
});
fs.rename可能不适合用在不同的disk中,直少在linux是这样,试试看,如果rename的path,target_path都是 C 或都是D drive的情形是否行?
为什么啊
出现中文乱码怎样解决
express 4.x里设置 app.use(express.bodyParser({uploadDir:'./upload_tmp'}));
这个报错