Node.js 上传文件

jopen 5年前

file.js文件

需要安装formidable 模块
var formidable = require('formidable');  var     http = require('http');  var     sys = require('sys');    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; charset=UTF-8'});              res.write('received upload:\n\n');                 res.end(sys.inspect({err:err, fields: fields, files: files}));           });           return;     }       // show a file upload form      res.writeHead(200, {'content-type': 'text/html; charset=UTF-8'});     res.end(           '<body>'+      '<form method="post" action="/upload" enctype="multipart/form-data">'+      'What is your name? <input type="text" name="name" /><br />'+      'What files are you sending? <input type="file" name="files" multiple="multiple" /><br />'+      '<input type="submit" value="send" />'+      '</form></body>'     );   }).listen(8888);  console.log("Server has started.");