Node js Express Rest API File Upload To MySQL Database

Nodejs express + MySQL + rest api image file upload example; In this tutorial, I will provide you complte guide through this how to upload image file into MySQL database in node js express using rest apis with multer package.

Multer is a middleware for handling multipart/form-data, extremely useful for managing file uploads. You can use Express. js middleware framework to build the single or multiple file upload system along with Multer and Node. js.

File Upload into MySQL database using Rest API in Node.js Express

  • Step 1 – Create New Node Js Application
  • Step 2 – Create Database and Table
  • Step 3 – Install Express , Body parse, mysql, cors and Multer Library
  • Step 4 – Connect App to Database
  • Step 5 – Create index.js file and Import Dependencies
  • Step 6 – Run File Upload into MySQL database using Rest API in Node.js Express App
  • Step 7 – File Upload To MySQL db By Calling Rest Api on Postman

Step 1 – Create New Node Js Application

Open your command prompt and execute the following command on it to create a new node js application:

mkdir my-node
cd my-node
npm init -y

Step 2 – Create Database and Table

Execute the following sql query to create a database and table:

CREATE DATABASE my-node;
 
CREATE TABLE `files` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step 3 – Install Express , Body parser, MySQL, cors and Multer Library

Install express, body parser, cors and multer library into your node js express application by executing the following command on command prompt:

npm install express body-parser mysql cors multer --save
  • Express  – Node.js Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
  • body-parser – Node.js request body parsing middleware which parses the incoming request body before your handlers, and make it available under req.body property. In other words, it simplifies the incoming request.
  • cors – It’s an Express middleware for enabling Cross-Origin Resource Sharing requests. Just because of it, We can access the API in different applications.
  • multer – Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.
  • mysql – MySQL is a relational database management system based on SQL – Structured Query Language. The application is used for a wide range of purposes, including data warehousing, e-commerce, and logging applications.

Step 4 – Connect App to Database

Connect app to database; so visit your app root directory and create a new file name database.js. Then add the following code into it to connect your app to database:

var mysql = require('mysql');
var conn = mysql.createConnection({
  host: 'localhost', // Replace with your host name
  user: 'root',      // Replace with your database username
  password: '',      // Replace with your database password
  database: 'my-node' // // Replace with your database Name
}); 

conn.connect(function(err) {
  if (err) throw err;
  console.log('Database is connected successfully !');
});
module.exports = conn;

Step 5 – Create index.js file and Import Libraries

Create index.js and import the above installed libararies. So visit your app root directory and create route for showing image upload and store image into directory, as shown below:

var express = require('express');
var path = require('path');
var cors = require('cors');
var bodyParser = require('body-parser');
var multer = require('multer')
var db=require('./database');

var app = express();
var port = process.env.PORT || 4000;
 
// enable CORS
app.use(cors());

// parse application/json
app.use(bodyParser.json());

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: true}));

// serving static files
app.use('/uploads', express.static('uploads'));
 
// request handlers
app.get('/', (req, res) => {
    res.send('Node js file upload rest apis');
});

// handle storage using multer
var storage = multer.diskStorage({
   destination: function (req, file, cb) {
      cb(null, 'uploads');
   },
   filename: function (req, file, cb) {
      cb(null, `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`);
   }
});

var upload = multer({ storage: storage });

// handle single file upload
app.post('/upload-file', upload.single('dataFile'), (req, res, next) => {
   const file = req.file;
   if (!file) {
      return res.status(400).send({ message: 'Please upload a file.' });
   }

   var sql = "INSERT INTO `file`(`name`) VALUES ('" + req.file.filename + "')";

   var query = db.query(sql, function(err, result) {
	   return res.send({ message: 'File uploaded successfully.', file });
	});

});

app.listen(port, () => {
    console.log('Server started on: ' + port);
});

The following multer package code will store images into directory. So the next step should be the create folder as “uploads” in the root directory where all our files will be saved.

// handle storage using multer
var storage = multer.diskStorage({
   destination: function (req, file, cb) {
      cb(null, 'uploads');
   },
   filename: function (req, file, cb) {
      cb(null, `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`);
   }
});

var upload = multer({ storage: storage });

The following routes will be handle the single uploaded file request and upload file into mysql database and directory in node express js app:

// handle single file upload
app.post('/uploadfile', upload.single('dataFile'), (req, res, next) => {
   const file = req.file;
   if (!file) {
      return res.status(400).send({ message: 'Please upload a file.' });
   }

   var sql = "INSERT INTO `file`(`name`) VALUES ('" + req.file.filename + "')";

   var query = db.query(sql, function(err, result) {
	   return res.send({ message: 'File uploaded successfully.', file });
	});

});

Step 6 – Run File Upload into MySQL database using Rest API in Node.js Express App

Open your command prompt and execute the following command to run node js express file upload application:

//run the below command

node index.js

Step 7 – File Upload To MySQL db By Calling Rest Api on Postman

Open your postman app and call node js express rest api to upload image file; you can see on the following image how to call node js express image upload rest api in postman app:

Conclusion

Node.js express file upload mysql rest api example; You have learned how to upload image file into mysql database in node js express using rest apis with multer package.

Recommended Node JS Tutorial

Be First to Comment

Leave a Reply

Your email address will not be published.