upload data to database with node js
Node js + MySQL + limited file upload rest API example; This tutorial volition show you from scratch how to upload file in MySQL database using node js express rest APIs with multer packet.
Note that, Multer is a node.js middleware for handlingmultipart/grade-data
, which is primarily used for uploading files. Information technology is written on top of busboy for maximum efficiency.
Throughout this tutorial steps, you will learn how to create file upload REST API using Node js + MySQL + Express js. Yous will also find out how to utilize multer in Node.js for treatment multipart/course-data for uploading files into MySQL database via remainder apis.
File Upload in MySQL Database using Node js Remainder Api
- Pace 1 – Create Node Express js App
- Footstep 2 – Install Limited + Mysql + Body parser + cors and Multer Library
- Footstep three – 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 post-obit 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 limited awarding by executing the following command on command prompt:
npm install limited torso-parser mysql cors multer --save
- Express — Node.js Express is a minimal and flexible Node.js web awarding 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 get in available underreq.body property. In other words, it simplifies the incoming asking.
- cors — It'southward an Limited middleware for enablingCross-Origin Resource Sharing requests. Just because of it, We tin can 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 management system (RDBMS).
Stride 3 – Create Database and Connect App to DB
Execute the following sql query to create a database and table:
CREATE DATABASE my-node; CREATE Tabular array `files` ( `id` int(11) Non NULL, `proper name` varchar(255) Non Goose egg, ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Then Connect app to database; then visit your app root directory and create a new file proper 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 name user: 'root', // Replace with your database username password: '', // Replace with your database countersign 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; equally shown below:
var express = require('limited'); 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 awarding/json app.use(bodyParser.json()); // parse application/10-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.ship('Node js file upload rest apis'); }); // handle storage using multer var storage = multer.diskStorage({ destination: office (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.mail('/upload-avatar', upload.single('dataFile'), (req, res, adjacent) => { const file = req.file; if (!file) { return res.condition(400).send({ message: 'Please upload a file.' }); } var sql = "INSERT INTO `file`(`name`) VALUES ('" + req.file.filename + "')"; var query = db.query(sql, role(err, outcome) { return res.send({ bulletin: 'File is successfully.', file }); }); }); app.heed(port, () => { console.log('Server started on: ' + port); });
Footstep 5 – Start Node Express Js App Server
Execute the post-obit command on last to start node limited js server:
//run the below control npm beginning after run this control open up your browser and striking http://127.0.0.ane:3000/upload-avatar
Pace six – Upload File using Rest Apis App
To upload files using rest apis; So open postman for sending HTTPmultipart/class-data
requests: equally shown below moving picture:
Conclusion
Node js express + MySQL rest API file upload example tutorial; you have learned how to build Residue 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 "upload data to database with node js"
Post a Comment