Node Js MySQL File Upload REST API Tutorial

Node Js MySQL File Upload REST API Tutorial

Node js MySQL image file upload rest API example; This tutorial will show you how to upload an image file into MySQL database in node js express using rest APIs with multer package.

Throughout this tutorial steps, you will learn how to create file upload REST API using Node js + MySQL + Express js to upload files in MySQL database. And, will also find out how to use multer in Node.js for handling multipart/form-data for uploading files into MySQL database via rest apis.

Node js Rest API File Upload to MySQL Database Example

Let’s follow the following steps to upload image file into MySQL database in node js express using REST API:

  • Step 1 – Create Node Express js App
  • Step 2 – Install Express + Mysql + Body parser + cors and Multer Library
  • Step 3 – Create Database and Connect App to DB
  • Step 3 – Create Server.js File
  • Step 4 – Start Node Express Js App Server
  • Step 5 – Upload File using Rest Api App

Step 1 – Create Node Express js App

Execute the following command on terminal to create node js app:

mkdir my-app
cd my-app
npm init

Step 2 – Install Express + Mysql + Body parser + 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 an open-source relational database management system (RDBMS).

Step 3 – Create Database and Connect App to DB

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;

Then 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 4 – Create Server.js File

Create server.js file and import express, mysql, multer, path dependencies in server.js and create file upload rest api route; 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 || 3000;
 
// 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-avatar', 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 is successfully.', file });
    });
});

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

Step 5 – Start Node Express Js App Server

Execute the following command on terminal to start node express js server:

//run the below command

npm start

after run this command open your browser and hit 

http://127.0.0.1:3000/upload-avatar

Step 6 – Upload File using Rest Apis App

To upload files using rest apis; So open postman for sending HTTP multipart/form-data requests: as shown below picture:

Node.js Rest Api File Upload in MySQL
Node.js Rest Api File Upload in MySQL

Conclusion

Node js express + MySQL rest API file upload example tutorial; you have learned how to build REST API for file uploading in MySQL database using rest API in Node.js, Express.js + Multer.

Recommended Node JS Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

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