-
-
Save dan085/3c261c336ab3873f86bf01bc00626088 to your computer and use it in GitHub Desktop.
Uploading files using NodeJS and Express 4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<body> | |
<form action="/upload" enctype="multipart/form-data" method="post"> | |
<input type="text" name="title"> | |
<input type="file" name="file"> | |
<input type="submit" value="Upload"> | |
</form> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* NodeJS code. | |
*/ | |
// Required modules. | |
var express = require('express'), | |
http = require('http'), | |
formidable = require('formidable'), | |
fs = require('fs'), | |
path = require('path'); | |
var app = express(); | |
// All your express server code goes here. | |
// ... | |
// Upload route. | |
app.post('/upload', function(req, res) { | |
var form = new formidable.IncomingForm(); | |
form.parse(req, function(err, fields, files) { | |
// `file` is the name of the <input> field of type `file` | |
var old_path = files.file.path, | |
file_size = files.file.size, | |
file_ext = files.file.name.split('.').pop(), | |
index = old_path.lastIndexOf('/') + 1, | |
file_name = old_path.substr(index), | |
new_path = path.join(process.env.PWD, '/uploads/', file_name + '.' + file_ext); | |
fs.readFile(old_path, function(err, data) { | |
fs.writeFile(new_path, data, function(err) { | |
fs.unlink(old_path, function(err) { | |
if (err) { | |
res.status(500); | |
res.json({'success': false}); | |
} else { | |
res.status(200); | |
res.json({'success': true}); | |
} | |
}); | |
}); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment