Node.js 上传文件

章节


Formidable 模块

“Formidable”模块是一个非常好的文件上传处理模块。

使用NPM下载安装该模块:

G:qikegu
odejs>npm install formidable

应用程序中导入这个模块:

var formidable = require('formidable');

上传文件

现在你可以用Node.js创建一个网页,让用户把文件上传到服务器:

步骤1:创建一个上传表单

创建一个Node.js文件,包含一个HTML表单,带有一个upload字段:

示例

这段代码将生成一个HTML表单:

var http = require('http');

http.createServer(function (req, res) {
  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);

步骤2:解析上传的文件

使用formidable模块,解析上传文件,文件奖杯放在临时文件夹中

示例

上传文件,并放到一个临时文件夹:

var http = require('http');
var formidable = require('formidable');

http.createServer(function (req, res) {
  if (req.url == '/fileupload') {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
      res.write('File uploaded');
      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);

步骤3:保存文件

当一个文件成功上传到服务器后,被放在一个临时文件夹中。

这个目录的路径可以在“files”对象中找到,该对象是parse()方法回调函数的第三个参数。

要移动文件,可使用文件系统模块:

示例

包含fs模块,将文件移动到目标文件夹:

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 = 'C:/Users/Your Name/' + 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);
原文地址:https://www.cnblogs.com/jinbuqi/p/11554979.html