In this tutorial, we'll discuss how to configure Multer, a node.js middleware used for handling multipart/form-data
, which is primarily used for uploading files. We will specifically focus on how to set it up to store files in cloud storage.
By the end of this tutorial, you will learn how to:
To follow along with this tutorial, you should have:
Understanding Cloud Storage:
Cloud storage is a service model in which data is maintained, managed, and backed up remotely and made available to users over a network. This allows us to save files without using local server space.
Setting up Multer:
Multer is a middleware that processes multipart/form-data
. It is mainly used for uploading files. To install Multer, use the following command:
npm install multer --save
Here is an example of setting up Multer with Google Cloud Storage:
const multer = require('multer');
const {Storage} = require('@google-cloud/storage');
const storage = new Storage({
projectId: 'your-project-id',
keyFilename: 'keyfile.json'
});
const bucket = storage.bucket('your-bucket-name');
const multerUpload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 5 * 1024 * 1024 },
}).single('file');
app.post('/upload', multerUpload, (req, res, next) => {
if (!req.file) {
res.status(400).send('No file uploaded.');
return;
}
const blob = bucket.file(req.file.originalname);
const blobStream = blob.createWriteStream();
blobStream.on('error', (err) => {
next(err);
});
blobStream.on('finish', () => {
res.status(200).send('File uploaded.');
});
blobStream.end(req.file.buffer);
});
In the above code:
In this tutorial, we've covered:
For further learning, you could explore how to configure Multer with other cloud storage services, or how to apply file validation before upload.
Set up a local server and implement file uploading with Multer, but without storing the file.
Modify the above server to store the uploaded file into local disk storage.
Further modify the server to store the uploaded file into Google Cloud Storage.
Remember to test your server with different file types and sizes. Happy coding!