LoginSignup
3
3

More than 5 years have passed since last update.

Node.jsでフォームからアップロードされたファイルを保存する

Last updated at Posted at 2015-09-01

hiroqn@github 氏より、以下のソースは間違いです。
やはりリクエストボディの解釈が必要ですので入力しないでください。

掲題の処理をする必要があったので少し調べてみたのですが、これだけでいけるようです。

var fs = require('fs');
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  if (req.method === 'GET') {
    res.end('<form method="post" enctype="multipart/form-data"><input type="file" name="file"><input type="submit"></form>');
  } else if (req.method === 'POST') {
    var out = fs.createWriteStream('save.jpg');
    req.pipe(out);
    res.end('end.');
  }
}).listen(3000);

localhost:3000にアクセスしてフォームからファイルをアップロードするとsave.jpgという名前で保存されます。

最初はbusboyなどでリクエストボディを解釈して保存する必要があるのかなと思っていたのですが、なぜパイプを繋ぐだけで保存できるのか、実はよく分かっていません。

3
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3