Node.js Upload Files
1.上传文件需要用到Formidable Module
,该Module通过npm install formidable
来下载
2.安装完成候引入:var formidable = require('formidable');
3.new一个IncomingForm对象: var form = new formidable.IncomingForm();
4.解析上传的文件:
form.parse(req, function (err, fields, files) {
res.write('File uploaded and moved!');
res.end();
5.通过fs Module来重命名上传的文件:
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.path;
var newpath = '/tmp/upload/' + files.filetoupload.name;
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
res.write('File uploaded and moved!');
res.end();
});
最后所有的完整代码如下:
var http = require('http');
var formidable = require('formidable');
var fs = require('fs');
http.createServer(function (req, res) {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.path;
var newpath = '/tmp/upload/' + files.filetoupload.name;
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
res.write('File uploaded and moved!');
res.end();
});
});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
}).listen(8080);