When a web client uploads a file to a server, it is generally submitted through a form and encoded as multipart/form-data
. Multer is middleware for Express and Node.js that makes it easy to handle this multipart/form-data
when your users upload files. In this tutorial, I’ll show you how to use this library to handle different file upload situations in Node.
How Does Multer Work?
As I said above, Multer is Express middleware. Middleware is a piece of software that connects different applications or software component. In Express, middleware processes and transforms incoming requests to the server. In our case, Multer acts as a helper when uploading files.
Project Setup
We will be using the Node Express framework for this project. Of course, you’ll need to have Node installed.
Create a directory for our project, navigate into the directory and issue npm init
to create a .json file that manages all the dependencies for our application.
mkdir upload-express cd upload-express npm init
Next, install Multer, Express and the other necessary dependencies necessary to bootstrap an express app.
npm install express multer body-parser --save
Next, create a server.js file.
touch server.js
Then, in server.js, we will initialize all the modules, create an express app and create a server for connecting to browsers.
// call all the required packages const express = require('express') const bodyParser= require('body-parser') const multer = require('multer'); app.use(bodyParser.urlencoded({extended: true})) const app = express() //CREATE EXPRESS APP const app = express(); //ROUTES WILL GO HERE app.get('/', function(req, res) { res.json({ message: 'WELCOME' }); }); app.listen(3000, () => console.log('Server started on port 3000'));
Running node server.js
and navigating to localhost:3000
on your browser should give you the following message.
Create the Client Code
The next thing will be to create an index.html file to write all the code that will be served to the client.
touch index.html
This file will contain the different forms that we will use for uploading our different file types.
MY APP
Open server.js and write a GET route that renders the index.html file instead of the “WELCOME” message.
// ROUTES app.get('/',function(req,res){ res.sendFile(__dirname + '/index.html'); });
Multer storage
The next thing will be to define a storage location for our files. Multer gives the option of storing files to disk as shown below. Here we set up a directory where all our files will be saved and we’ll also give the files a new identifier.
//server.js // SET STORAGE var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'uploads') }, filename: function (req, file, cb) { cb(null, file.fieldname + '-' + Date.now()) } }) var upload = multer({ storage: storage })
Handling File Uploads
Uploading a Single File
In the index.html file, we defined an action attribute that performs a POST request. Now we need to create an endpoint in the Express application. Open the server.js file and add the following code:
app.post('/uploadfile', upload.single('myFile'), (req, res, next) => { const file = req.file if (!file) { const error = new Error('Please upload a file') error.httpStatusCode = 400 return next(error) } res.send(file) })
Note that the name of the file field should be the same as the myFile
argument passed to the upload.single
function.
Uploading Multiple Files
Uploading multiple files with Multer is similar to a single file upload but a few changes.
//Uploading multiple files app.post('/uploadmultiple', upload.array('myFiles', 12), (req, res, next) => { const files = req.files if (!files) { const error = new Error('Please choose files') error.httpStatusCode = 400 return next(error) } res.send(files) })
Uploading Images
Instead of saving uploaded images to the file system, we will store them in a MongoDB database so that we can retrieve them later as needed. But first, let’s install MongoDB.
npm install mongodb --save
We will then connect to MongoDB through the Mongo.client
method and then add the MongoDB URL to that method. You can use a cloud service like Mlab which offers a free plan or simply use the locally available connection.
const MongoClient = require('mongodb').MongoClient const myurl = 'mongodb://localhost:27017'; MongoClient.connect(myurl, (err, client) => { if (err) return console.log(err) db = client.db('test') app.listen(3000, () => { console.log('listening on 3000') }) })
Open server.js and define a POST request that enables saving images to the database.
app.post('/uploadphoto', upload.single('picture'), (req, res) => { var img = fs.readFileSync(req.file.path); var encode_image = img.toString('base64'); // Define a JSONobject for the image attributes for saving to database var finalImg = { contentType: req.file.mimetype, image: new Buffer(encode_image, 'base64') }; db.collection('quotes').insertOne(finalImg, (err, result) => { console.log(result) if (err) return console.log(err) console.log('saved to database') res.redirect('/') }) })
In the above code, we first encode the image to a base64 string, construct a new buffer from the base64 encoded string and then save it to our database collection in JSON format.
We then display a success message and redirect the user to the index page.
Retrieving Stored Images
To retrieve the stored images, we perform a mongodb search using the find
method and return an array of results. We then go on and obtain the _id
attributes of all the images and return them to the user.
app.get('/photos', (req, res) => { db.collection('mycollection').find().toArray((err, result) => { const imgArray= result.map(element => element._id); console.log(imgArray); if (err) return console.log(err) res.send(imgArray) }) });
Since we already know the id’s of the images, we can view an image by passing its id in the browser as illustrated below.
app.get('/photo/:id', (req, res) => { var filename = req.params.id; db.collection('mycollection').findOne({'_id': ObjectId(filename) }, (err, result) => { if (err) return console.log(err) res.contentType('image/jpeg'); res.send(result.image.buffer) }) })
Conclusion
I hope you found this tutorial helpful. File upload can be an intimidating topic, but it doesn’t have to be hard to implement. With Express and Multer, handling multipart/form-data
is easy and straight forward. You can find the full source code for the file upload example in our GitHub repo.
Powered by WPeMatico