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:
multerpackage installation -$ npm install --save multer- File upload route - creates a route to handle the file upload, using
multeranddiskStorage - File retrieval route - creates a route to serve the file
Helpful links
More of Expressjs
- How do I use adm-zip with Express.js?
- How can I use express-zip js to zip and download files?
- How can I disable the X-Powered-By header in Express.js?
- How do I write unit tests for ExpressJS?
- What is Express.js?
- How do I use an express.js query parser?
- How can I use Zipkin to trace requests in Express.js?
- How do Express.js and Spring Boot compare in terms of features and performance?
- How can I use Express.js to implement websockets in my application?
- How can I configure Express.js to use Nginx as a reverse proxy?
See more codes...