Node/Express file upload
Solution 1:
ExpressJS Issue:
Most of the middleware is removed from express 4. check out: http://www.github.com/senchalabs/connect#middleware For multipart middleware like busboy, busboy-connect, formidable, flow, parted is needed.
This example works using connect-busboy middleware.
create /img and /public folders.
Use the folder structure:
\server.js
\img\"where stuff is uploaded to"
\public\index.html
SERVER.JS
var express = require('express'); //Express Web Server
var busboy = require('connect-busboy'); //middleware for form/file upload
var path = require('path'); //used for file path
var fs = require('fs-extra'); //File System - for file manipulation
var app = express();
app.use(busboy());
app.use(express.static(path.join(__dirname, 'public')));
/* ==========================================================
Create a Route (/upload) to handle the Form submission
(handle POST requests to /upload)
Express v4 Route definition
============================================================ */
app.route('/upload')
.post(function (req, res, next) {
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
console.log("Uploading: " + filename);
//Path where image will be uploaded
fstream = fs.createWriteStream(__dirname + '/img/' + filename);
file.pipe(fstream);
fstream.on('close', function () {
console.log("Upload Finished of " + filename);
res.redirect('back'); //where to go next
});
});
});
var server = app.listen(3030, function() {
console.log('Listening on port %d', server.address().port);
});
INDEX.HTML
<!DOCTYPE html>
<html lang="en" ng-app="APP">
<head>
<meta charset="UTF-8">
<title>angular file upload</title>
</head>
<body>
<form method='post' action='upload' enctype="multipart/form-data">
<input type='file' name='fileUploaded'>
<input type='submit'>
</body>
</html>
The following will work with formidable SERVER.JS
var express = require('express'); //Express Web Server
var bodyParser = require('body-parser'); //connects bodyParsing middleware
var formidable = require('formidable');
var path = require('path'); //used for file path
var fs =require('fs-extra'); //File System-needed for renaming file etc
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
/* ==========================================================
bodyParser() required to allow Express to see the uploaded files
============================================================ */
app.use(bodyParser({defer: true}));
app.route('/upload')
.post(function (req, res, next) {
var form = new formidable.IncomingForm();
//Formidable uploads to operating systems tmp dir by default
form.uploadDir = "./img"; //set upload directory
form.keepExtensions = true; //keep file extension
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
console.log("form.bytesReceived");
//TESTING
console.log("file size: "+JSON.stringify(files.fileUploaded.size));
console.log("file path: "+JSON.stringify(files.fileUploaded.path));
console.log("file name: "+JSON.stringify(files.fileUploaded.name));
console.log("file type: "+JSON.stringify(files.fileUploaded.type));
console.log("astModifiedDate: "+JSON.stringify(files.fileUploaded.lastModifiedDate));
//Formidable changes the name of the uploaded file
//Rename the file to its original name
fs.rename(files.fileUploaded.path, './img/'+files.fileUploaded.name, function(err) {
if (err)
throw err;
console.log('renamed complete');
});
res.end();
});
});
var server = app.listen(3030, function() {
console.log('Listening on port %d', server.address().port);
});
Solution 2:
Another option is to use multer, which uses busboy under the hood, but is simpler to set up.
var multer = require('multer');
Use multer and set the destination for the upload:
app.use(multer({dest:'./uploads/'}));
Create a form in your view, enctype='multipart/form-data
is required for multer to work:
form(role="form", action="/", method="post", enctype="multipart/form-data")
div(class="form-group")
label Upload File
input(type="file", name="myfile", id="myfile")
Then in your POST you can access the data about the file:
app.post('/', function(req, res) {
console.dir(req.files);
});
A full tutorial on this can be found here.
Solution 3:
I find this, simple and efficient:
const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();
// default options
app.use(fileUpload());
app.post('/upload', function(req, res) {
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.');
}
// The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
let sampleFile = req.files.sampleFile;
// Use the mv() method to place the file somewhere on your server
sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) {
if (err)
return res.status(500).send(err);
res.send('File uploaded!');
});
});
express-fileupload
Solution 4:
Here is a simplified version (the gist) of Mick Cullen's answer -- in part to prove that it needn't be very complex to implement this; in part to give a quick reference for anyone who isn't interested in reading pages and pages of code.
You have to make you app use connect-busboy:
var busboy = require("connect-busboy");
app.use(busboy());
This will not do anything until you trigger it. Within the call that handles uploading, do the following:
app.post("/upload", function(req, res) {
if(req.busboy) {
req.busboy.on("file", function(fieldName, fileStream, fileName, encoding, mimeType) {
//Handle file stream here
});
return req.pipe(req.busboy);
}
//Something went wrong -- busboy was not loaded
});
Let's break this down:
- You check if
req.busboy
is set (the middleware was loaded correctly) - You set up a
"file"
listener onreq.busboy
- You pipe the contents of
req
toreq.busboy
Inside the file listener there are a couple of interesting things, but what really matters is the fileStream
: this is a Readable, that can then be written to a file, like you usually would.
Pitfall: You must handle this Readable, or express will never respond to the request, see the busboy API (file section).