https://grokonez.com/node-js/nodejs-save-file-image-to-mysql-by-sequelize-with-blob-type
NodeJS – Save File/Image to MySQL by Sequelize with BLOB type
In the tutorial, we will show how to build a NodeJS application to save files/images to MySQL database by Sequelize with BLOB type.
Related posts:
Sequelize save file/image to MySQL
Firstly, we define a Sequelize model for files/images with BLOB type as below:
const Image = sequelize.define('image', {
...
data: {
type: Sequelize.BLOB('long')
}
});
To read/write data of file/image, we use fs.readFileSync('/path/to/file')
and fs.writeFileSync('/path/to/file', image.data)
functions of NodeJS file-system module.
Below segment code is used to store file/image to MySQL:
var fs = require('fs');
...
var imageData = fs.readFileSync('/path/to/file');
Image.create({
...
data: imageData
}).then(image => {
try{
fs.writeFileSync('/path/to/file', image.data);
}catch(e){
console.log(e);
}
})
Practice
We build a NodeJS project as below structure:
More at:
https://grokonez.com/node-js/nodejs-save-file-image-to-mysql-by-sequelize-with-blob-type
NodeJS – Save File/Image to MySQL by Sequelize with BLOB type
Top comments (0)