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 files in Node.Js?
in node.js, for file upload you can use various module for file upload. these modules are :
you can download Formidable module and installed using NPM:
File Name :
C:\Users>mahtab_nodejs>npm install formidable
############################# OR ###############################
C:\Users>mahtab_nodejs>npm install multer
npm version multer
npm install ejs
npm install express
npm install multer
After download you can include the module in any application:
var formidable = require('formidable');
How to upload Files?
File Name : file_upload.js
var http = require('http');
var formidable = require('formidable');
var fs = require('fs');
http.createServer(function (req, res) {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.filepath;
var newpath = 'C:/Users/Your Name/' + files.filetoupload.originalFilename;
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
res.write('File uploaded and moved!');
res.end();
});
});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
}).listen(8080);
First Include the Formidable module to be able to parse the uploaded file once it reaches the server.
When the file is uploaded and parsed, it gets placed on a temporary folder on your computer.
When a file is successfully uploaded to the server, it is placed on a temporary folder.
The path to this directory can be found in the "files" object, passed as the third argument in the parse() method's callback function.
To move the file to the folder of your choice, use the File System module, and rename the file:
signup
File Name : signup.js
<!DOCTYPE html>
<html>
<head>
<title>FILE UPLOAD DEMO</title>
</head>
<body>
<h1>Single File Upload Demo</h1>
<form action="/uploadProfilePicture"
enctype="multipart/form-data" method="POST">
<span>Upload Profile Picture:</span>
<input type="file" name="mypic" required/> <br>
<input type="submit" value="submit">
</form>
</body>
</html>
index.js
File Name : index.js
const express = require("express")
const path = require("path")
const multer = require("multer")
const app = express()
// View Engine Setup
app.set("views",path.join(__dirname,"views"))
app.set("view engine","ejs")
// var upload = multer({ dest: "Upload_folder_name" })
// If you do not want to use diskStorage then uncomment it
var storage = multer.diskStorage({
destination: function (req, file, cb) {
// Uploads is the Upload_folder_name
cb(null, "uploads")
},
filename: function (req, file, cb) {
cb(null, file.fieldname + "-" + Date.now()+".jpg")
}
})
// Define the maximum size for uploading
// picture i.e. 1 MB. it is optional
const maxSize = 1 * 1000 * 1000;
var upload = multer({
storage: storage,
limits: { fileSize: maxSize },
fileFilter: function (req, file, cb){
// Set the filetypes, it is optional
var filetypes = /jpeg|jpg|png/;
var mimetype = filetypes.test(file.mimetype);
var extname = filetypes.test(path.extname(
file.originalname).toLowerCase());
if (mimetype && extname) {
return cb(null, true);
}
cb("Error: File upload only supports the "
+ "following filetypes - " + filetypes);
}
// mypic is the name of file attribute
}).single("mypic");
app.get("/",function(req,res){
res.render("Signup");
})
app.post("/uploadProfilePicture",function (req, res, next) {
// Error MiddleWare for multer file upload, so if any
// error occurs, the image would not be uploaded!
upload(req,res,function(err) {
if(err) {
// ERROR occured (here it can be occured due
// to uploading image of size greater than
// 1MB or uploading different file type)
res.send(err)
}
else {
// SUCCESS, image successfully uploaded
res.send("Success, Image uploaded!")
}
})
})
// Take any port number of your choice which
// is not taken by any other process
app.listen(8080,function(error) {
if(error) throw error
console.log("Server created Successfully on PORT 8080")
})
Run for output :-
node index.js