ファイルあぷろだ実装
下記エントリの実装を参考に、あぷろどのみな機能を盛り込んだプロトタイプを作って動作確認してみたんですが、さくっと動きました。
以下な形でフォームを作っておいて
<form method="post" enctype="multipart/form-data" action="/file-upload"> <input type="text" name="username"> <input type="password" name="password"> <input type="file" name="thumbnail"> <input type="submit"> </form>
あとは app.post で /file-upload なナニを定義したら req.files.thumnail であぷしたファイルな情報を受けることができる模様。
また、あぷろどされたファイルは一旦
app.use(express.bodyParser({uploadDir:'./uploads'}));
に置かれて post な手続きオブジェクトの中で mv してますね。定義が以下。
app.post('/file-upload', function(req, res) { // get the temporary location of the file var tmp_path = req.files.thumbnail.path; // set where the file should actually exists - in this case it is in the "images" directory var target_path = './public/images/' + req.files.thumbnail.name; // move the file from the temporary location to the intended location fs.rename(tmp_path, target_path, function(err) { if (err) throw err; // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files fs.unlink(tmp_path, function() { if (err) throw err; res.send('File uploaded to: ' + target_path + ' - ' + req.files.thumbnail.size + ' bytes'); }); }); });
このままだとファイル名がカブッたりとかユーザ認証が、とか MongoDB と云々という余地があるので引き続きもくもくの方向。