upload the file from nodejs
This blog we have seen mongodb basic and how is it
work with installation and after installation, we have already seen
mongodb basic, CRUD operation, connect mongodb with nodejs, read, update,
delete, POST, GET API etc.
we should not face
any problem while making Database, collection(table) and using the data in nodejs even whenever we will make
API. Read data from mongodb in nodejs
- # What is Mongoose
-
# Install Mongoose
-
# Install Multer npm package
-
# Make Router for upload file
Now in this blog we will use mongoose. There is an
npm package to connect nodes to mongodb. Mongoose is a MongoDB object modeling tool designed to work
in an asynchronous environment. They created mongoose by improving
mongodb, with the help of which you can create schemas and models of mongoose's
movements.
Suppose that there are 4 fields in our database (like name, brand, price, category) and the user wants to add a 5th field also (like color) but we want
to add only 4 fields, for this we create schemas.
Here you can also define TYPE in schemas like price type is
numeric but if any user wants to use quotes (" " ' ') then we can stop the
user for this.
in sort we can apply validation in mongoose but we
can't in directly mongodb.
What is MongoDB
MongoDB is a popular open-source NoSQL (non-relational) database management system. NoSQL means no structure like it is look like an object while in SQL it is a structure query language like SELECT CustomerName, City FROM Customers; (The SELECT statement is used to select data from a database.) But NoSQL database is useless...NOT completely because of whenever we want add extra column in database then it is possible through NoSQL MongoDB.
MongoDB installation - CLICK HERE
MongoDB Basic Command -
CLICK HERE
About MongoDB vs SQL - CLICK HERE
CRUD in MongoDB - CLICK HERE
Object Like -
{ "_id": { "$oid": "659ad46e0382148123c82841" }, "name": "moto G60", "brand": "motorola", "price": 16500, "category": "mobile" }
MongoDB is a type of database that helps store and manage large amounts
of data in a flexible and scalable way. Unlike SQL, MongoDB doesn't require a
fixed structure for the data, allowing you to store information in a more
versatile format.
- MongoDB is a NoSQL database.
- The data stored in a collection
- Collection don't have row and columns
- Data is stored in the form of object.
Install Mongoose
For this you need to copy this (npm i mongoose) and paste it in project's
terminal.
Install Multer npm package
First we need to install multer npm package in our project, if you want you can also write the code without this npm package. Let's first install it.
Simple go this link -
CLICK HERE
CMD for installation - npm i multer
Make Router for upload file
Now we will write code of upload file with the npm package multer but first we
will send data POST method and using /upload endpoint and also you can
create a folder named as uploads.
const express = require('express') const multer = require('multer'); const app = express(); app.post("/upload" , (req, resp) => { resp.send("File uploaded") }); app.listen(8000)
const upload = multer({ storage: multer.diskStorage({ destination:function(req, file, cb) { cb(null,'uploads/') //folder to save the files in }, filename:function(req, file, cb) { // cb(null, file.fieldname + "-" + Date.now() + ".jpg" ) //if you can extract extension from file then use this code var ext=file.originalname.split("."); if(ext[ext.length-1]==='jpg' || ext[ext.length -1 ] === 'png'){ cb(null , file.fieldname+ '-' +Date.now()+"."+ext[ext.length -1]); }else{ cb(new Error('Error : Only jpg and png are allowed')); } } }) }).single("user_file");// field name in form data
Let's breakdown the code.
1) Multer Configuration:
const upload = multer({
storage: multer.diskStorage({
// ... configuration options ...
})
}).single("user_file");
# upload: This variable holds the configured multer middleware.
It's set up to handle a single file upload.
# multer: This is the
Multer middleware.
# storage: Multer's storage option defines how
files should be stored. In this case, it uses multer.diskStorage to specify
that files should be stored on the disk.
multer.diskStorage({
destination: function(req,
file, cb) {
cb(null,
'uploads/');
},
filename:
function(req, file, cb) {
//
... filename configuration ...
}
})
destination: A function that determines the
destination folder for storing uploaded files. In this example, it's set to
'uploads/'. You need to make sure the 'uploads' directory exists in your
project.
filename: A function that determines the name of the
uploaded file. It checks the file extension and appends a timestamp to the
original filename if it's a jpg or png file. If the file extension is not
allowed, it throws an error.
3) Error Handling:
if (ext[ext.length - 1] === 'jpg' || ext[ext.length - 1] === 'png') {
cb(null, file.fieldname + '-' + Date.now() + '.' + ext[ext.length - 1]);
}
else {
cb(new Error('Error: Only jpg and png are
allowed'));
}
This part of the code checks the file extension. If
the extension is 'jpg' or 'png', it generates a filename with the original
fieldname, a timestamp, and the file extension. If the extension is not
allowed, it invokes the callback with an error.
}).single("user_file");
The .single("user_file") part specifies that
it's expecting a single file upload with the field name "user_file". The field
name should match the one used in your HTML form's file input.
Whole Code
const express = require('express') const multer = require('multer'); const app = express(); const upload = multer({ storage: multer.diskStorage({ destination:function(req, file, cb) { cb(null,'uploads/') //folder to save the files in }, filename:function(req, file, cb) { var ext=file.originalname.split("."); if(ext[ext.length-1]==='jpg' || ext[ext.length -1 ] === 'png'){ cb(null , file.fieldname+ '-' +Date.now()+"."+ext[ext.length -1]); }else{ cb(new Error('Error : Only jpg and png are allowed')); } } }) }).single("user_file");// field name in form data app.post("/upload", upload , (req, resp) => { resp.send("File uploaded") }); app.listen(8000)
Disclaimer
All tutorials are for informational and educational purposes only and have been made using our own routers, servers, websites and other vulnerable free resources. we do not contain any illegal activity. We believe that ethical hacking, information security and cyber security should be familiar subjects to anyone using digital information and computers. Hacking Truth is against misuse of the information and we strongly suggest against it. Please regard the word hacking as ethical hacking or penetration testing every time this word is used. We do not promote, encourage, support or excite any illegal activity or hacking.
0 comments:
Post a Comment
For Any Tech Updates, Hacking News, Internet, Computer, Technology and related to IT Field Articles Follow Our Blog.