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 ORM – Build CRUD RestAPIs with NodeJs/Express, Sequelize, MySQL

Sequelize save file/image to MySQL

Firstly, we define a Sequelize model for files/images with BLOB type as below:

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:

Practice

We build a NodeJS project as below structure:

Setting up NodeJS project

Init NodeJs project by commandline: npm init

Install Sequelize and MySQL dependencies:

-> ‘package.json’ file:

Sequelize Image model

./app/model/img.model.js file:

Configure Sequelize MySQL Connection

– Config file ./app/config/env.js:

– Setup Sequelize-MySQL connection in ./app/config/db.config.js file:

Save File/Image to MySQL

app.js file:

Run & Check results

Start NodeJs server:
-> Server’s Logs

-> Database’ table:

nodejs-save-file-image-to-mysql-by-sequelize

Sourcecode

NodeJS-Save-File-Image-To-MySQL-by-Sequelize

By JavaSampleApproach | May 1, 2018.

Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*