Storing Uploaded Files in a Database Nodejs
Node js + MySQL + express file upload rest API example; This tutorial will evidence you from scratch how to upload file in MySQL database using node js express rest APIs with multer package.
Note that, Multer is a node.js middleware for treatmentmultipart/form-data
, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.
Throughout this tutorial steps, y'all 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-information for uploading files into MySQL database via rest apis.
File Upload in MySQL Database using Node js Rest Api
- Step ane – 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 three – Create Server.js File
- Footstep iv – Start Node Express Js App Server
- Step 5 – Upload File using Rest Api App
Step 1 – Create Node Limited js App
Execute the following command on terminal to create node js app:
mkdir my-app cd my-app npm init
Pace 2 – Install Limited + Mysql + Body parser + cors and Multer Library
Install express, body parser, cors and multer library into your node js express application past executing the post-obit 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 spider web and mobile applications.
- torso-parser — Node.js request trunk parsing middleware which parses the incoming request body earlier your handlers, and make information technology available underreq.trunk property. In other words, it simplifies the incoming request.
- cors — It'due south an Express middleware for enablingCross-Origin Resource Sharing requests. Just because of it, We tin access the API in different applications.
- multer — Multer is a node.js middleware for handlingmultipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.
- MySQL — MySQLan open-source relational database direction arrangement (RDBMS).
Step iii – 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 Zip, `proper name` varchar(255) Non NULL, ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Then Connect app to database; then visit your app root directory and create a new file name database.js. Then add together 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 proper name user: 'root', // Replace with your database username password: '', // Replace with your database password database: 'my-node' // // Supercede with your database Name }); conn.connect(part(err) { if (err) throw err; console.log('Database is connected successfully !'); }); module.exports = conn;
Footstep 4 – Create Server.js File
Create server.js file and import express, mysql, multer, path dependencies in server.js and create file upload residue api route; every bit 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.apply(cors()); // parse application/json app.use(bodyParser.json()); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({extended: true})); // serving static files app.apply('/uploads', express.static('uploads')); // request handlers app.get('/', (req, res) => { res.transport('Node js file upload rest apis'); }); // handle storage using multer var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(nil, 'uploads'); }, filename: function (req, file, cb) { cb(null, `${file.fieldname}-${Date.at present()}${path.extname(file.originalname)}`); } }); var upload = multer({ storage: storage }); // handle single file upload app.postal service('/upload-avatar', upload.unmarried('dataFile'), (req, res, adjacent) => { const file = req.file; if (!file) { return res.status(400).send({ bulletin: 'Please upload a file.' }); } var sql = "INSERT INTO `file`(`proper name`) VALUES ('" + req.file.filename + "')"; var query = db.query(sql, function(err, outcome) { return res.send({ message: 'File is successfully.', file }); }); }); app.listen(port, () => { panel.log('Server started on: ' + port); });
Step 5 – Start Node Express Js App Server
Execute the following control on terminal to starting time node limited js server:
//run the below command npm beginning later on run this control open your browser and hit http://127.0.0.ane:3000/upload-avatar
Stride six – Upload File using Rest Apis App
To upload files using rest apis; So open postman for sending HTTPmultipart/form-data
requests: as shown below picture:

Determination
Node js express + MySQL rest API file upload case tutorial; you accept learned how to build Remainder API for file uploading in MySQL database using rest API in Node.js, Express.js + Multer.
Recommended Node JS Tutorials
Source: https://www.tutsmake.com/node-js-mysql-rest-api-file-upload/
0 Response to "Storing Uploaded Files in a Database Nodejs"
Post a Comment