How to File Upload REST API using Node Js MySQL?

27-Dec-2022

.

Admin

How to File Upload REST API using Node Js MySQL?

Hello Friends,

In this tutorial, we will create a very simple way to rest API for Image Uploading using node js and multer. we will use express, multer, and body-parser npm packages for creating image uploads with node.js and multer.

Throughout this tutorial steps, you will learn how to create file upload REST API using Node js + MySQL + Express js. You 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.

Step 1: Create Node Express js App


Execute the following command on the terminal to create the 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 the 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 makes it available under req.body property. In other words, it simplifies incoming requests.
  • 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 the 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 the app to the 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 the 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, and 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 the terminal to start the node express js server:

    //run the below command

    npm start

    After running 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

    I hope it can help you...

    #Node JS