Nodejs file upload

在server端需要加入,主要為上傳到暫存資料夾,然後刪除再將檔案移動至想要的資料夾中
app.post('/upload', function(req, res){
data = req.body;
// get the temporary location of the file
console.log('file => '+req.files);
var tmp_path = req.files.file.path;
// set where the file should actually exists - in this case it is in the "images" directory
var target_path = './public/images/'+ req.files.file.name;
// move the file from the temporary location to the intended location
console.log('tmp_path = '+tmp_path+' || target_path = '+target_path);
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('upload success!');
});
});
});
view raw app.js hosted with ❤ by GitHub


html使用form方式加入,使用bootstrap的CSS將畫面美化
<form class="form-horizontal" action="/upload" method="post" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label">File upload</label>
<div class="controls">
<input type="file" name="file" class="btn-large">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-large btn-primary">Submit</button>
</div>
</div>
</form>
view raw upload.html hosted with ❤ by GitHub


相關連結
Twitter Bootstrap
Nodejs

沒有留言:

張貼留言