Skip to content

Instantly share code, notes, and snippets.

@primayudantra
Forked from paambaati/upload_demo_html.html
Created November 15, 2017 05:05
Show Gist options
  • Save primayudantra/b88bd1df6c788e3a2984837a5046bd62 to your computer and use it in GitHub Desktop.
Save primayudantra/b88bd1df6c788e3a2984837a5046bd62 to your computer and use it in GitHub Desktop.
Uploading files using NodeJS and Express 4
<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>
/*
* 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