Node.js/Express에서 간단한 파일 업로드
11909 단어 Node.jsExpressJadeCoffeeScript
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")
이제 양식이 보일 것입니다.
![](https://s1.md5.ltd/image/4d0079a41eae86c099e22d246aadfefc.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');
});
});
};
이제 다음과 같이 업로드할 수 있게 된다.
![](https://s1.md5.ltd/image/5bf61fc2e856dcad2a938dbc0ef63f09.png)
블로그를하고 있습니다 : PAPA-tronix!
Reference
이 문제에 관하여(Node.js/Express에서 간단한 파일 업로드), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/Feel-Physics/items/55390c60ba4a1d1fe5cd텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)