30
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.js/Express4でのシンプルなファイルのアップロード

Posted at

はじめに

大体、Node.js/Expressでのシンプルなファイルのアップロードの記事でOK

express4固有の対応

expressコマンドがない

Express 4 をはじめようでこれを知りました。記事にある通り、「express-generator」を入れることで、expressコマンドが使えます。

npm install -g express-generator

expressコマンドでひな形の作成

express upload
$ cd upload
$ npm install
$ mkdir uploads

bodyParser

bodyParserがJSONのみ対象になったので、expressjs/multerを使った。

npm install --save multer
app.use(multer({ dest: './uploads/'}))

アップロードファイルの処理

元記事のnameだとmulterだと一時ファイル名だったので、originalnameに変更

upload.js
var fs;

fs = require('fs');

exports.post = function(req, res) {
  var target_path, tmp_path;
  console.dir(req.files);
  tmp_path = req.files.thumbnail.path;
  target_path = './uploads/' + req.files.thumbnail.originalname;
  fs.rename(tmp_path, target_path, function(err) {
    if (err) {
      throw err;
    }
    fs.unlink(tmp_path, function() {
      if (err) {
        throw err;
      }
      res.send('File uploaded to: ' + target_path + ' - ' + req.files.thumbnail.size + ' bytes');
    });
  });
};

まとめ

bodyParserがイマイチ理解できてない状態で書いてますorz。
upload.jsでの処理は、multerではapp.useの中に書くことも出来る模様。

30
29
0

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
30
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?