Skip to content

Instantly share code, notes, and snippets.

@paambaati
Last active March 28, 2021 14:55
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save paambaati/db2df71d80f20c10857d to your computer and use it in GitHub Desktop.
Save paambaati/db2df71d80f20c10857d 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});
}
});
});
});
});
});
@diasor
Copy link

diasor commented Sep 14, 2018

@cannap super useful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment