OpenClassrooms devient une université américaine accréditée.
Découvrez ce que cela change pour vousTable des matières
- Partie 1
Build a Simple Express Server
- Partie 2
Build a RESTful API
- Partie 3
Make Your API Secure
- Partie 4
Add Image Upload to Your API
Accept Incoming Files With Multer
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
storageconstant — to be passed tomulteras configuration, which contains the logic necessary for tellingmulterwhere to save incoming files.The
destinationfunction tellsmulterto save files in theimagesfolder.The
filenamefunction tellsmulterto 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 yourstorageconstant, and telling it that you will be handling uploads of single image files.
#Let's Recap!
multeris 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!
- Formations jusqu’à 100 % financées
- Date de début flexible
- Projets professionnalisants
- Mentorat individuel