NodeJs Tutorials
- NodeJs
- Install NodeJs
- Why use NodeJs
- NodeJs Process Model
- create First Application
- Run NodeJs Application
- Node.js Console
- Node.Js Modules
- URL Modules
- node.js Callback
- Node.js Events
- Upload Files
- Upload single & Multiple Files
- NodeJs File System
- NodeJs Email
- Debugging NodeJs
- .ENV
- NodeJs Mysql
- Helpers
- encription and decription in nodeJs
- Query string
- Date & Time
- Express Js
- Template Engine with Express
- MVC Pattern in Node.Js
- list of NPM Module
- Middleware
- Body Parser
- Render
- Nodemon module
- Morgan module
- Flash Message in ExpressJs
- Session
- Session store in database
- Cookies
- Helmet
- Multer
- Router: How To Use Routing In Node.Js
- App.Js
- express.json() and express.urlencoded()
- REST APIs in NodeJs
- Gloabal Objects
- Submit Form Data
- How to get Post Data in Node.js
- How to Get URL Parameters in Node.js
- How to create Node Project
- How to Insert Form Data Into the MySql Table Using Node.js
- How to fetch Data from MySQL database table using Node.js
- CRUD Example
- Await and Async
- Promises
- Login Example
- Password Encription
- How to validate Form (Form Validation) in Node.Js?
- Registration & Login form usingn Node.Js & MySql?
- Forgot & Reset Password
- File Upload in Node.Js with ExpressJs
- Resize Image Before Upload using Multer Sharp
- Upload multiple file using node.js with multer module
- Upload file using node.js with multer module
- Client IP Address
- REST API Downloading File in NodeJs
- Export and Download CSV From MySQL Database
- CRUD REST API
- CRUD REST API Example 2
- Enable HTTPS using Node
- How to send EMAIL using NodeJs?
- Dynamic dependent dropdown using NodeJs?
- Autocomplete Search
- Get and Send Data From Ajax Request
- Get and Post Data using Ajax
- Passport Authentication
- Node Js Data type
- Node Js Error
- Node Js Array Function
- Node Js String Function
- Puppeter Module
How to upload file in NodeJs with MySql?
Install Multer module
File Name :
npm install express multer body-parser mysql
############## OR ##############
npm install --save multer
Create Html form to upload file.
File Name : index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>How to upload file in NodeJs with MySql? ittutorial.in</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>How to store image path in MySQL database using Node js - Tutsmake.com</h1>
<form action="/" enctype="multipart/form-data" method="post">
<input type="file" name="image" accept='image/*' >
<input type="submit" value="Upload">
</form>
</body>
</html>
Create Server.js File
File Name : server.js
const express = require('express')
const app = express()
const bodyparser = require('body-parser')
const mysql = require('mysql')
const multer = require('multer')
const path = require('path')
//use express static folder
app.use(express.static("./public"))
// body-parser middleware use
app.use(bodyparser.json())
app.use(bodyparser.urlencoded({
extended: true
}))
// Database connection
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "test"
})
db.connect(function (err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
})
//! Use of Multer
var storage = multer.diskStorage({
destination: (req, file, callBack) => {
callBack(null, './public/images/') // './public/images/' directory name where save the file
},
filename: (req, file, callBack) => {
callBack(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})
var upload = multer({
storage: storage
});
//! Routes start
//route for Home page
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
//@type POST
//route for post data
app.post("/post", upload.single('image'), (req, res) => {
if (!req.file) {
console.log("No file upload");
} else {
console.log(req.file.filename)
var imgsrc = 'http://127.0.0.1:3000/images/' + req.file.filename
var insertData = "INSERT INTO users_file(file_src)VALUES(?)"
db.query(insertData, [imgsrc], (err, result) => {
if (err) throw err
console.log("file uploaded")
})
}
});
//create connection
const PORT = process.env.PORT || 3000
app.listen(PORT, () => console.log(`Server is running at port ${PORT}`))
Example 2 :-
File Name : index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>How to Resize Image Before Upload using Multer - ittutorial.in</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Resize Image Before Upload using Multer</h1>
<form action="/" enctype="multipart/form-data" method="post">
<input type="file" name="image" accept='image/*'>
<input type="submit" value="Upload">
</form>
</body>
</html>
server.js
File Name : server.js
const express = require('express');
const multer = require('multer');
const path = require('path');
const sharp = require('sharp');
const fs = require('fs');
const app = express();
const 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.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.post('/', upload.single('image'),async (req, res) => {
const { filename: image } = req.file;
await sharp(req.file.path)
.resize(200, 200)
.jpeg({ quality: 90 })
.toFile(
path.resolve(req.file.destination,'resized',image)
)
fs.unlinkSync(req.file.path)
res.redirect('/');
});
app.listen(3000);
run app
File Name :
node server.js
File Upload in NodeJs using REST API
Install Express and Multer module
File Name :
npm install express multer body-parser --save
npm install sharp --save
Create Server.js File
File Name : server.js
var express = require("express");
var multer = require('multer');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage}).single('userPhoto');
app.post('upload-myfile',function(req,res){
upload(req,res,function(err) {
if(err) {
return res.end("Error occurs in uploading file.");
}
res.end("File is uploaded successfully");
});
});
app.listen(3000,function(){
console.log("App run on port 3000");
});
Start Node ExpressJs App Server
File Name :
npm start
##################3 OR ##############
node server.js
Output :-
http://127.0.0.1:3000/upload-myfile
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.
Install Express + Mysql + Body parser + cors and Multer Library
File Name :
npm install express body-parser mysql cors multer --save
File Name :
CREATE TABLE `files` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
create server
File Name : server.js
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.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);
});
File Name :