In this final part of the course, you will learn how to implement file uploads to allow users to upload images of items they want to sell. To do this, you will use multer
, a package that allows you to handle incoming files in HTTP requests. So let's start by installing multer
and building a piece of middleware to handle those incoming files.
Set Up File Handling Middleware
First you need to install multer
to your project:
npm install multer
Now you can create a new piece of middleware in your middleware
folder called multer-config.js
:
const multer = require('multer');
const MIME_TYPES = {
'image/jpg': 'jpg',
'image/jpeg': 'jpg',
'image/png': 'png'
};
const storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, 'images');
},
filename: (req, file, callback) => {
const name = file.originalname.split(' ').join('_');
const extension = MIME_TYPES[file.mimetype];
callback(null, name + Date.now() + '.' + extension);
}
});
module.exports = multer({storage: storage}).single('image');
In this middleware:
Create a
storage
constant — to be passed tomulter
as configuration, which contains the logic necessary for tellingmulter
where to save incoming files.The
destination
function tellsmulter
to save files in theimages
folder.The
filename
function tellsmulter
to use the original name, replacing any spaces with underscores and adding aDate.now()
timestamp, as the file name; it then uses the MIME type map constant to resolve the appropriate file extension.
You then export the fully configured
multer
, passing it yourstorage
constant, and telling it that you will be handling uploads of single image files.
Let's Recap!
multer
is a file-handling package.Multer's
diskStorage()
sets up the destination path and filename for incoming files.Multer's
single()
method creates middleware which captures single files of the type passed as an argument and uses the set storage method to save it to the server's filesystem.
Before you can apply your middleware to your stuff routes, you need to modify them slightly, as the structure of the incoming data is not quite the same when there are files and JSON data. This is what we will do in the next chapter!