Table of Content
Resize Image using multer & sharp and Upload to MySQL in node js
Last modified: May 18, 20221. Install Libraries
- install i sharp
- install i multer
2. Upload and Resize the image and then upload to MySQL
const multer = require('multer')
const { Readable } = require("stream"); // from nodejs
const sharp = require("sharp");
const db = require('../db/models/index');
const Image = db.image;
app.post("/api/image/upload/:userId" , multer().single('uploadfile'), async function(request, response){
const file = request.file
const buffer = file.buffer
sharp(buffer)
.resize(500)
.jpeg({ quality: 90 })
.toBuffer((err, data, info) => {
try {
const image = Image.create({
image: Buffer.from(data).toString('base64'),
filename:file.filename,
userId: request.params.userId
}).then(msg => {
response.send({ message: "Image was registered uploaded!" });
})
} catch (error) {
console.log(error);
}
});
});
To display
- Read the record from database
- For example below
<img src="data:image/png;base64, base64-code-from-database" />