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
Upload single and multiple files in NodeJs?
https://afteracademy.com/blog/file-upload-with-multer-in-nodejs-and-express
DiskStorage
The disk storage engine gives you full control over storing files to disk. We will create a storage object using the diskStorage() method.
File Name :
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './uploads');
},
filename: function (req, file, cb) {
cb(null , file.originalname);
}
});
###################### OR ######################
var storage = multer.diskStorage({
destination: (req, file, callBack) => {
callBack(null, './public/images/')
},
filename: (req, file, callBack) => {
callBack(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})
Here we use two function destination and filename.
The 2 arguments to cb are:
Other Options :-
limits :- You can set a limit on the size of the file that is being uploaded.
const upload = multer({
storage: storage,
limits : {fileSize : 2000000},
// limits: { fileSize: 1 * 1024 * 1024 }, // 1MB
fileFilter: (req, file, cb) => {
if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
cb(null, true);
} else {
cb(null, false);
const err = new Error('Only .png, .jpg and .jpeg format allowed!')
err.name = 'ExtensionError'
return cb(err);
}
},
});
fileSize is in bytes. (2000000 bytes = 2MB)
fileFilter :-
fileFilter function to control which files should be uploaded and Not.
File Name :
function fileFilter (req, file, cb) {
// To reject this file pass `false`, like so:
cb(null, false);
// To accept the file pass `true`, like so:
cb(null, true);
// You can always pass an error if something goes wrong:
cb(new Error('I don\'t have a clue!'));
}
Example
File Name :
function fileFilter (req, file, cb) {
// Extensio of file Allowed
const filetypes = /jpeg|jpg|png|gif/;
// Check extension
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
// Check mimetype
const mimetype = filetypes.test(file.mimetype);
if(mimetype && extname){
return cb(null,true);
} else {
cb('Error: Only Images!');
}
}
Uploading Multiple Files using multer
function .arrays('fieldname',max_count) that accepts an array of files, all with the name fieldname. It generates an error if more than max_count files are uploaded. The array of files will be stored in req.files.
File Name :
app.post("/images_upload", upload.array("my_files", 10), (req, res) =>{
try {
res.send(req.files);
} catch (error) {
console.log(error);
res.send(400);
}
});
File Name :
// Use of Multer
var storage = multer.diskStorage({
destination: (req, file, callBack) => {
callBack(null, './public/images/')
//callBack(null, path.join(__dirname, './images/'))
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
// cb(null, file.fieldname + '-' + Date.now() + file.originalname.match(/\..*$/)[0])
}
})
var upload = multer({ storage: storage }); // for single file upload
// var upload = multer({ storage : storage }).array('userPhoto',10); // for multiple file upload
// ########## multiple file upload start ###############
router.get('/upload-multiple-files', function(req,res){
res.render('upload-multiple-file', {title: 'Upload Multiple files'})
})
router.post('/upload_multiple', upload.array('resume',10), (req, res) => {
var file = req.files;
console.log(file);
if(file.length > 0 )
{
console.log("yes");
}
else{
console.log("no");
}
res.redirect('/users/upload-multiple-files');
});
// ############ multiple file upload end. ##################
Single file upload
File Name :
router.post('/save_user', upload.single('resume'), function(req, res, next){
// router.post('/save_user', function(req, res, next){
if (!req.file) {
console.log("File not uploaded!");
}
else
{
var file_neme = req.file.filename;
// console.log(req.file.filename)
}
/* upload(req,res,function(err) {
if(err) {
// return res.end("Error uploading multiple file.");
console.log("File not uploaded!");
}
var file_neme = req.file.filename;
// res.end("multiple File is uploaded");
});
*/
})
File Name :
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/tmp/my-uploads')
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, file.fieldname + '-' + uniqueSuffix)
}
})
File Name :
.single(fieldname)
Accept a single file with the name fieldname. The single file will be stored in req.file.
.array(fieldname[, maxCount])
Accept an array of files, all with the name fieldname. Optionally error out if more than maxCount files are uploaded. The array of files will be stored in req.files.
.fields(fields)
Accept a mix of files, specified by fields. An object with arrays of files will be stored in req.files.
.none()
Accept only text fields. If any file upload is made, error with code "LIMIT_UNEXPECTED_FILE" will be issued.
.any()
Accepts all files that comes over the wire. An array of files will be stored in req.files.
uploading multiple files
File Name :
router.post('/upload_multiple', upload.array('resume',10), (req, res) => {
var file = req.files;
// console.log(file);
if(file.length > 0 )
{
for(i = 0; i < file.length; i++)
{
const docname = req.files[i];
console.log(docname.filename);
}
}
else{
console.log("no");
}
res.redirect('/users/upload-multiple-files');
});
File Name :