Skip to content

Instantly share code, notes, and snippets.

@IskenHuang
Created September 26, 2012 03:10
Show Gist options
  • Save IskenHuang/3785774 to your computer and use it in GitHub Desktop.
Save IskenHuang/3785774 to your computer and use it in GitHub Desktop.
Nodejs file upload
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!');
});
});
});
<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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment