出典:node.jsのいろいろなモジュール5 – node-formidableでアップロード

formidableモジュール

 Node.jsのファイルアップロード用モジュール
 まずは、formidableモジュールが既にインストールされているかの確認を行う。

$ npm ls

インストールされているモジュールの一覧がでて、インストールが必要ならば、

$ npm install formidable@latest

ファイルアップロード

Webサーバー起動
$ node app
app.jsの動作確認

 Webブラウザでhttp://raspberrypi:3000/を開く
 /へのリクエストで、ファイルアップロード用ページが開く
 input type=”file” で1つのファイルを選び(ファイル名の変更が面倒で複数ファイルには対応していない)
 input type=”submit” value=”アップロード” ボタンを押すことで
 /uploadリクエストで、選択したファイルが/TMPへアップロードされる。
 後はよく分からない。formidableのソースを見る必要があるかも、自分には無理。
 注意:アップロードしただけだと、英数字を羅列したファイル名になるので、renameをして元のファイル名と同じにしているが、/tmpに同名のファイルがあると上書きされるので注意。

app.js
let http = require('http'),
    formidable = require('formidable'),
    fs = require('fs'),
    server;

//ファイル保存場所
const TEST_TMP="/tmp";
//ポート番号
const TEST_PORT=3000;

server = http.createServer(function(req, res) {
  if (req.url == '/') { //'/'へのリクエスト
    res.writeHead(200, {'content-type': 'text/html'});
    res.write('<form action="/fileupload" enctype="multipart/form-data" method="post">');
    res.write('<input type="text" name="title"><br>');
    res.write('<input type="file" name="fileupload"><br>');
    res.write('<input type="submit" value="アップロード">');
    res.write('</form>');
    return res.end();
  } else if (req.url == '/fileupload') { //'/fileupload'へのリクエスト
    let form = new formidable.IncomingForm();
    form.parse(req, function (err,fields,files){
      let oldpath = files.filetoupload.filepath;
      let newpath = '/tmp/' + files.filetoupload.originalFilename;
      fs.rename(oldpath,newpath,function(err) {
        if(err) throw err;
        res.write('File uploaded and moved!');
        res.end();
      });
    });   
  } else {
    res.writeHead(404, {'content-type': 'text/plain'});
    res.end('404');
  }
});
server.listen(TEST_PORT);
console.log('listening on http://raspberrypi:'+TEST_PORT+'/');