Nodejs Multer File Upload to Db Blog

Node js + MySQL + limited file upload balance API example; This tutorial will evidence you from scratch how to upload file in MySQL database using node js limited residuum APIs with multer package.

Note that, Multer is a node.js middleware for handlingmultipart/form-information, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.

Throughout this tutorial steps, yous will acquire how to create file upload REST API using Node js + MySQL + Express js. Y'all will as well find out how to utilise multer in Node.js for handling multipart/form-information for uploading files into MySQL database via balance apis.

File Upload in MySQL Database using Node js Rest Api

  • Step ane – Create Node Express js App
  • Step 2 – Install Limited + Mysql + Torso parser + cors and Multer Library
  • Step 3 – Create Database and Connect App to DB
  • Step 3 – Create Server.js File
  • Pace 4 – Offset Node Express Js App Server
  • Step 5 – Upload File using Residuum Api App

Step one – Create Node Limited js App

Execute the following command on last 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 control on command prompt:

npm install limited body-parser mysql cors multer --save
  • Express  — Node.js Express is a minimal and flexible Node.js web application framework that provides a robust fix of features for web and mobile applications.
  • trunk-parser — Node.js request body parsing middleware which parses the incoming request trunk before your handlers, and make information technology available underreq.trunk belongings. In other words, information technology simplifies the incoming asking.
  • cors — It's an Express middleware for enablingCantankerous-Origin Resource Sharing requests. Just considering of it, We can access the API in different applications.
  • multer — Multer is a node.js middleware for handlingmultipart/course-information, which is primarily used for uploading files. It is written on acme of busboy for maximum efficiency.
  • MySQL — MySQLan open-source relational database management system (RDBMS).

Pace 3 – Create Database and Connect App to DB

Execute the post-obit sql query to create a database and table:

CREATE DATABASE my-node;   CREATE Table `files` (   `id` int(11) NOT Nothing,   `name` varchar(255) Not Zip, ) ENGINE=InnoDB DEFAULT CHARSET=latin1;          

And then Connect app to database; and so visit your app root directory and create a new file name database.js. Then add together the following code into information technology to connect your app to database:

var mysql = require('mysql'); var conn = mysql.createConnection({   host: 'localhost', // Replace with your host name   user: 'root',      // Supervene upon 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 iv – 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 = crave('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.use(cors()); // parse application/json app.use(bodyParser.json()); // parse application/ten-www-form-urlencoded app.utilise(bodyParser.urlencoded({extended: true})); // serving static files app.use('/uploads', express.static('uploads'));   // request handlers app.go('/', (req, res) => {     res.send('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(nix, `${file.fieldname}-${Appointment.now()}${path.extname(file.originalname)}`);    } });  var upload = multer({ storage: storage });  // handle single file upload app.post('/upload-avatar', upload.unmarried('dataFile'), (req, res, next) => {    const file = req.file;    if (!file) {       render res.condition(400).send({ message: 'Please upload a file.' });    }    var sql = "INSERT INTO `file`(`proper name`) VALUES ('" + req.file.filename + "')";    var query = db.query(sql, office(err, event) {        render res.send({ bulletin: 'File is successfully.', file });     }); });  app.listen(port, () => {     panel.log('Server started on: ' + port); });          

Step 5 – Commencement Node Express Js App Server

Execute the post-obit command on final to start node express js server:

//run the below command  npm commencement  after run this command open up your browser and hit   http://127.0.0.1:3000/upload-avatar

Footstep vi – Upload File using Rest Apis App

To upload files using residual apis; So open postman for sending HTTPmultipart/course-data requests: every bit shown below movie:

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; yous have learned how to build Residue API for file uploading in MySQL database using residual API in Node.js, Express.js + Multer.

Recommended Node JS Tutorials

southrinte1987.blogspot.com

Source: https://www.tutsmake.com/node-js-mysql-rest-api-file-upload/

0 Response to "Nodejs Multer File Upload to Db Blog"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel