在 Node 中使用 formidable 处理文件上传
具体使用方式参照官方文档:https://www.npmjs.com/package/formidable
第一:安装:
代码语言:javascript复制# npm install --save formidable
yarn add formidable
第二:基本使用:
代码语言:javascript复制var formidable = require('formidable'),
http = require('http'),
util = require('util');
http.createServer(function(req, res) {
if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
// parse a file upload
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:nn');
res.end(util.inspect({fields: fields, files: files}));
});
return;
}
// show a file upload form
res.writeHead(200, {'content-type': 'text/html'});
res.end(
'<form action="/upload" enctype="multipart/form-data" method="post">'
'<input type="text" name="title"><br>'
'<input type="file" name="upload" multiple="multiple"><br>'
'<input type="submit" value="Upload">'
'</form>'
);
}).listen(8080);