Skip to content

Instantly share code, notes, and snippets.

@saumyasuhagiya
Last active March 26, 2020 07:48
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save saumyasuhagiya/bd29a46533a726960c10c79b1b8b4445 to your computer and use it in GitHub Desktop.
Save saumyasuhagiya/bd29a46533a726960c10c79b1b8b4445 to your computer and use it in GitHub Desktop.
Mysql blob image retrieval and insert operation using sequelize package of node.js
var DATABASE_NAME = 'test_db';
var DB_USERNAME = 'abc';
var DB_PASSWORD = 'abc@123';
var Sequelize = require('sequelize');
var FS = require('fs');
var sequelize = new Sequelize(
DATABASE_NAME,
DB_USERNAME,
DB_PASSWORD, {
host:'localhost',
port:3306,
dialect:'mysql',
define: {
freezeTableName: true
}
});
//Connect to Database
sequelize.authenticate().then(function (e) {
if(e) {
console.log('There is connection ERROR');
} else {
console.log('Connection has been established successfully');
}
});
//Create Table: image
var Image_Store = sequelize.define('image', {
image_id: {
type: Sequelize.INTEGER
},
image_type: {
type: Sequelize.STRING,
allowNull: false
},
image: {
type: Sequelize.BLOB('long')
},
image_size: {
type: Sequelize.INTEGER
},
image_name: {
type: Sequelize.STRING
}
});
sequelize.sync({
force: true,
logging: console.log
}).then(function () {
console.log('Everything is synced');
//Give any image name here.
var imageData = FS.readFileSync(__dirname + '/123_icon.png');
Image_Store.create({
image_id: 123,
image_type: 'png',
image: imageData,
image_size: 3,
image_name: 'FileName'
}).then(function (image_store) {
try {
//console.log(image_store.image)
FS.writeFileSync(__dirname + '/target.png', image_store.image);
} catch (e) {
console.log(e+'');
}
});
});
@borellaster
Copy link

Hello,

I'm trying to do something similar here in my Api. The create method is OK, but when I execute the writeFileSync method, it generate a file , corrupted (1kb).
Do you have any ideia why it happens?

fs.writeFileSync(__dirname + '/target.jpg', object.file);

Thanks in advance.

Felipe

@albertotorresfoltyn
Copy link

I'm not sure, but maybe the problem is that is not base64encoded/decoded?

@amanbansal86
Copy link

are you able to solve it ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment