Node Js MySQL File Upload REST API Example Tutorial

To upload the file image to MySQL database and node js app; Simply install Multer, MySQL modules, and create REST API with the help of these modules in Node Express JS application and use REST API with Postman application to upload.

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

Steps to upload image file into MySQL database in node js express using REST API via postman:

Step 1 – Create Node js App

Simply open your cmd or terminal window and run the following command into it to create node js application or project:

mkdir my-app
cd my-app
npm init
mkdir uploads

Step 2 – Install Express + Mysql + Body parser + cors and Multer Library

To install express, body parser, cors and multer modules into your node js application by running the npm install express body-parser mysql cors multer --save command on cmd or 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 and Connect Database to App

To create database and table, you can use the following sql query:

CREATE DATABASE my_node;

CREATE TABLE `files` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Next, navigate to your node express js application root directory and create a new file name database.js, and 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 and Import Modules

To navigate to your node express app root directory and create server.js file, and then import express, mysql, multer, path modules into it; like following:

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'));


// 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 });


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

And create route to upload image file to MySQL database and node express application folder; Make it like the following and add it to your server.js file:

// request handlers and testing route
app.get('/', (req, res) => {
    res.send('Node js file upload rest apis');
});

// upload image file in mysql db and app folder
app.post('/file-upload', upload.single('file'), (req, res, next) => {
   const file = req.file;
   if (!file) {
      return res.status(400).send({ message: 'Please upload a file.' });
   }
   var sql = "INSERT INTO `files`(`name`) VALUES ('" + req.file.filename + "')";
   var query = db.query(sql, function(err, result) {
       return res.send({ message: 'File is successfully.', file });
    });
});

Step 5 – Start Node Express Js App Server

Type the npm start on cmd or terminal and press enter 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/file-upload

Step 6 – Upload File to MySQL Database in Node js using Rest Apis via Postman

Simply start your Postman application and use rest API with HTTP multipart/form-data to upload image file in MySQL database and node express js folder using rest APIs and postman; like the following:

file upload in node js using postman via rest api
file upload in node js using postman via rest api

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

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including 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. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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