LoginSignup
58
65

More than 5 years have passed since last update.

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

Last updated at Posted at 2013-08-14

基本的に以下のページと同じ内容です。

Node.js/ExpressJSでのファイルのアップロード
http://d.hatena.ne.jp/zebevogue/20120828/1346140796

ただし、何カ所か修正する必要がありました。

expressコマンド

$ express upload
$ cd upload
$ npm install
$ mkdir uploads

流れとしては
1. get '/'routes/index.js#index が呼ばれてフォームを表示し、
2. post 'upload'routes/upload.js#upload が呼ばれてアップロードされたファイルを処理する
という感じで良い。

まず1.からやる。

app.jsを編集する

下記のように編集する

app.js
var routes = {
    index  : require('./routes/index'),
};
...
app.get('/', routes.index.index);
...

routes/index.js

個人的趣味でCoffeeScriptで書いた。-bオプションを付けたcoffee -bcw index.coffeeコマンドで変換するので、 app.js からでも中まで見える。というか、デフォルトそのまま。

exports.index = (req, res) ->
  res.render 'index',{
    title: 'Express'
  }
index.js
exports.index = function(req, res) {
  res.render('index', {
    title: 'Express'
  });
};

参照する index.jade テンプレートにフォームを記述する。

index.jade
extends layout

block content
  form(method="post", enctype="multipart/form-data", action="/upload")
    input(type="file", name="thumbnail")
    input(type="submit")

これでフォームが見えるはず。

スクリーンショット 2013-08-14 11.15.18.png

次に2.をやる

app.js

app.js
var routes = {
    index  : require('./routes/index'),
    upload : require('./routes/upload')
};
...

app.configure(function(){
    ...
    //app.use(express.bodyParser());
    app.use(express.bodyParser({uploadDir:'./uploads'}));
    ...
});

app.get('/', routes.index.index);
app.post('/upload', routes.upload.post);
...

routes/upload.js

upload.coffee
fs = require 'fs'
exports.post = (req, res) ->
  # 一時ファイルのパス
  tmp_path = req.files.thumbnail.path
  # public以下に置くパス
  target_path = './uploads/' + req.files.thumbnail.name
  # public以下に移動
  fs.rename tmp_path, target_path, (err) ->
    if err then throw err
    # 一時ファイルを削除
    fs.unlink tmp_path, ->
      if err then throw err
      res.send 'File uploaded to: ' + target_path + ' - ' + req.files.thumbnail.size + ' bytes'
upload.js
var fs;

fs = require('fs');

exports.post = function(req, res) {
  var target_path, tmp_path;
  tmp_path = req.files.thumbnail.path;
  target_path = './uploads/' + req.files.thumbnail.name;
  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');
    });
  });
};

これで以下のようにアップロードできるようになる。

スクリーンショット 2013-08-14 11.18.54.png


ブログやってます:PAPA-tronix !

58
65
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
58
65