expressjsHow do I store and retrieve a blob using Express.js?
Storing and retrieving a blob using Express.js is a relatively simple process.
First, you need to install the multer
package which provides a middleware for handling multipart/form-data, which is necessary for uploading files.
$ npm install --save multer
Once installed, you can create a route in your Express app to handle the file upload.
const multer = require('multer');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './uploads');
},
filename: (req, file, cb) => {
cb(null, `${file.fieldname}-${Date.now()}`);
},
});
const upload = multer({ storage });
app.post('/upload', upload.single('myFile'), (req, res) => {
// req.file is the `myFile` file
// req.body will hold the text fields, if there were any
});
To retrieve the blob, you can simply create a route in your Express app that serves the file.
app.get('/uploads/:file', (req, res) => {
const file = req.params.file;
const filePath = path.join(__dirname, 'uploads', file);
res.download(filePath);
});
The parts of the code are:
multer
package installation -$ npm install --save multer
- File upload route - creates a route to handle the file upload, using
multer
anddiskStorage
- File retrieval route - creates a route to serve the file
Helpful links
More of Expressjs
- How can I use Node.js and Express together to create a web application?
- How do I find Express.js tutorials on YouTube?
- How can I use Express.js and websockets together to create real-time applications?
- How can I configure Express.js to use Nginx as a reverse proxy?
- How do I use Zod with Express.js?
- How can I use Express.js to prevent XSS attacks?
- How can I use Express.js to develop a web application?
- How do I use Express.js to handle x-www-form-urlencoded data?
- How can I use an ExpressJS webhook to receive data from an external source?
- How do I use Express.js to parse YAML files?
See more codes...