Node.js/Express에서 간단한 파일 업로드

기본적으로 다음 페이지와 같은 내용입니다.

Node.js/ExpressJS에서 파일 업로드
htp // d. 하테나. 네. jp/제베ㅉ구에/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")

이제 양식이 보일 것입니다.



그런 다음 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');
    });
  });
};

이제 다음과 같이 업로드할 수 있게 된다.



블로그를하고 있습니다 : PAPA-tronix!

좋은 웹페이지 즐겨찾기