NodeJS/Express – RestAPI to Upload Multipart File to MySQL using Multer + Sequelize ORM

In the tutorial, we show how to build a NodeJS/Express RestAPI to upload Multipart Files/Images to MySQL using Multer middleware and Sequelize ORM.

Related posts:
NodeJS – Save File/Image to MySQL by Sequelize with BLOB type
Multer – Build RestAPI to upload a MultipartFile to NodeJS/Express

Goal

Prerequisites

NodeJS – Save File/Image to MySQL by Sequelize with BLOB type
Multer – Build RestAPI to upload a MultipartFile to NodeJS/Express

Objective

In the tutorial, we create a NodeJS project that build RestAPI to upload files/images to MySQL database, see below project structure:

Using PostMan to make a POST request:

NodeJS-Express-Multer-Upload-MultipartFile-MySQL-Sequelize-upload-from-postman

-> result:

NodeJS-Express-Multer-Upload-MultipartFile-MySQL-Sequelize-saving-to-mysql table

Practice

Setting up NodeJS/Express project

Create a folder ‘NodeJS-Express-Multer-Upload-MultipartFile-Sequelize-MySQL’:

Then init NodeJS project:

-> Install Express, Multer, Sequelize, MySQL:

-> See package.json file:

NodeJS Application
Sequelize Image model

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

Multer Upload

– Create ./app/config/upload.config.js file:

Configure Sequelize MySQL Connection

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

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

Upload Router

./app/routers/upload.router.js file:

Upload Controller

./app/controllers/upload.controller.js file:

Server.js

server.js file:

Run & Check results

Start NodeJS server:

Make a POST request:

NodeJS-Express-Multer-Upload-MultipartFile-MySQL-Sequelize-upload-from-postman

-> Server Logs:

-> Uploaded File:

NodeJS-Express-Multer-Upload-MultipartFile-MySQL-Sequelize-saving-to-diskstorage

-> MySQL table:

NodeJS-Express-Multer-Upload-MultipartFile-MySQL-Sequelize-saving-to-mysql table

-> Load file from MySQL:

NodeJS-Express-Multer-Upload-MultipartFile-MySQL-Sequelize-saving-to-load-from-mysql

Sourcecode

To run below sourcecode, follow the guides:


step 0: download & extract zip file -> we have a folder ‘NodeJS-Express-Multer-Upload-MultipartFile-Sequelize-MySQL’
step 1: cd NodeJS-Express-Multer-Upload-MultipartFile-Sequelize-MySQL
step 2: npm install express multer sequelize mysql2 –save
step 3: node server.js
step 4: makes a POST request: http://localhost:8081/api/uploadfile

-> Sourcecode:

NodeJS-Express-Multer-Upload-MultipartFile-Sequelize-MySQL

By grokonez | May 16, 2018.



Related Posts


Got Something To Say:

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

*