How to Create a Pdf Upload on Moongoose
Upload and Call back Image on MongoDB using Mongoose
Prerequisites: For getting started with this you should have some familiarity with NodeJS, ExpressJS, MongoDB and Mongoose.
- NodeJS : It is a complimentary open source server environment that uses JavaScript on the server and runs on various platform (Windows, Linux, Unix, Mac OS Ten, etc.).It uses asynchronous programming.
- ExpressJS : Information technology is a NodeJS web application server framework, designed for building single-page, multi-page, and hybrid web applications. Information technology is the de facto standard server framework for node.
- MongoDB : MongoDB is a NoSQL database.MongoDB is a JSON document datastore. It allows you lot to store and query JSON style documents with a few smarts on tiptop.
- Mongoose : Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node. js. Information technology manages relationships betwixt data, provides schema validation, and is used to translate between objects in lawmaking and the representation of those objects in MongoDB.
To starting time, install the required packages and modules:
- ExpressJS allows us to prepare upwards middleware to respond to HTTP Requests.
npm install limited --save
- The module "body-parser" enables reading (parsing) HTTP-POST data.
npm install torso-parser --relieve
- Mongoose is a MongoDB client library providing object-modelling for use in an asynchronous environment. Mongoose supports both promises and callbacks.
npm install mongoose --salvage
- Multer is nodejs middleware used for uploading files.
npm install multer --relieve
- Dotenv is a zip-dependency module that loads environment variables from a .env file into process.env.
npm install dotenv --save
- EJS (Embedded Javascript) is a templating engine for nodejs. This engine helps to create an HTML pages via templates with minimal code.
npm install ejs --save
- nodemon is a developer tool that automatically restarts the node application when file changes in the lawmaking directory are detected. Information technology improves the developer feel when working on node-based applications. Since this is a development tool and not role of our application lawmaking, we utilize `–salvage-dev` when installing this module:
npm install nodemon --relieve-dev
Now let'due south starting time coding! To upload an paradigm and retrieve image by MongoDB using Mangoose, follow each of the steps below one past one.
- Stride 0: Create the file ` .env ` that will incorporate surroundings-specific settings.
Javascript
MONGO_URL=mongodb:
PORT=3000
- Stride 1: Create our server file ` app.js `. Add together the post-obit code to information technology:
Javascript
var express = require( 'express' )
var app = express()
var bodyParser = require( 'body-parser' );
var mongoose = require( 'mongoose' )
var fs = crave( 'fs' );
var path = crave( 'path' );
require( 'dotenv/config' );
- Pace 2: Connect to MongoDB using the URL for your database. Here 'procedure.env.MONGO_URL' is used for the database URL. This value is retrieved from ` .env ` as an environment variable past the module `dotenv`. Add the following code to ` app.js `
Javascript
mongoose.connect(process.env.MONGO_URL,
{ useNewUrlParser: true , useUnifiedTopology: true }, err => {
panel.log( 'connected' )
});
- Step three: Once nosotros have established a connectedness to our database and required all the necessary packages, we tin can now begin defining our server-side logic. And then for storing an image in MongoDB, nosotros need to create a schema with mongoose. For that create the file ` model.js ` file and define the schema. The important point hither is that our data blazon for the image is a Buffer which allows the states to shop our image as data in the form of arrays.
Javascript
var mongoose = require( 'mongoose' );
var imageSchema = new mongoose.Schema({
name: String,
desc: String,
img:
{
information: Buffer,
contentType: Cord
}
});
module.exports = new mongoose.model( 'Image' , imageSchema);
- Footstep iv: We want to set EJS equally our templating engine with Express. EJS is specifically designed for edifice single-page, multi-page, and hybrid spider web applications. Information technology has get the standard server framework for nodejs. The default behavior of EJS is that it looks into the ` views ` folder for the templates to render. We will create our templates in a later on step.
Add the post-obit lawmaking to ` app.js `:
Javascript
app.apply(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.set( "view engine" , "ejs" );
- Step 5: Nosotros will define the storage path for the image we are uploading. Here, we are using the middleware Multer to upload the photo to the server in a folder called ` uploads ` so nosotros tin process it.
Add the following code to ` app.js `:
Javascript
var multer = require( 'multer' );
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb( cypher , 'uploads' )
},
filename: (req, file, cb) => {
cb( null , file.fieldname + '-' + Date.now())
}
});
var upload = multer({ storage: storage });
- Step 6: At present, load the Image model past adding the post-obit code to ` app.js `:
Javascript
var imgModel = require( './model' );
- Step vii: Prepare the handler for the GET request to our server. The response displays an HTML page showing all the images stored in the database, and provides a UI for uploading new images.
Add together the following code to ` app.js `:
Javascript
app.go( '/' , (req, res) => {
imgModel.detect({}, (err, items) => {
if (err) {
panel.log(err);
res.status(500).send( 'An mistake occurred' , err);
}
else {
res.render( 'imagesPage' , { items: items });
}
});
});
- Step 8: Handle the Postal service request that processes the form data submitted by the user from our HTML UI. This asking will have the new images being uploaded.
Add the following code to ` app.js `:
Javascript
app.mail( '/' , upload.single( 'image' ), (req, res, next) => {
var obj = {
name: req.body.proper noun,
desc: req.body.desc,
img: {
data: fs.readFileSync(path.bring together(__dirname + '/uploads/' + req.file.filename)),
contentType: 'image/png'
}
}
imgModel.create(obj, (err, detail) => {
if (err) {
panel.log(err);
}
else {
res.redirect( '/' );
}
});
});
- Step ix: Configure the server to default port with the default of 3000 . The surround variable procedure.env.PORT is used if set in your ` .env `.
Add together the following code to ` app.js `:
Javascript
var port = process.env.PORT || '3000 '
app.listen(port, err => {
if (err)
throw err
console.log(' Server listening on port', port)
})
- Footstep 10: This is the HTML template for the "upload page". Notice that the src parameter for the <img> is not a typical URL. This format enables displaying the epitome stored in binary format in the Mongo database, and we convert it to base64 so that the browser can return it.
Add the following code to the ` views/imagesPage.ejs `:
HTML
<!DOCTYPE html>
< html lang = "en" >
< caput >
< meta charset = "UTF-eight" >
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" >
< title >Paradigm Uploading</ title >
</ head >
< body >
< h1 >To Upload Image on mongoDB</ h1 >
< hr >
< div >
< form activeness = "/" method = "Mail" enctype = "multipart/class-data" >
< div >
< label for = "proper name" >Epitome Title</ label >
< input type = "text" id = "proper noun" placeholder = "Name"
value = "" proper name = "name" required>
</ div >
< div >
< characterization for = "desc" >Prototype Clarification</ characterization >
< textarea id = "desc" proper name = "desc" value = "" rows = "ii"
placeholder = "Clarification" required>
</ textarea >
</ div >
< div >
< characterization for = "image" >Upload Image</ label >
< input type = "file" id = "image"
name = "image" value = "" required>
</ div >
< div >
< button type = "submit" >Submit</ button >
</ div >
</ form >
</ div >
< 60 minutes >
< h1 >Uploaded Images</ h1 >
< div >
<% items.forEach(function(epitome) { %>
< div >
< div >
< img src="data:image/<%=image.img.contentType%>;base64,
<%=image.img.information.toString('base64')%>">
< div >
< h5 ><%= image.name %></ h5 >
< p ><%= paradigm.desc %></ p >
</ div >
</ div >
</ div >
<% }) %>
</ div >
</ body >
</ html >
- Step 11: Create the directory ` uploads ` that will hold our uploaded images. The code in Step 8 refers to this directory.
- Step 12: Start the server past running the command: ` nodemon app.js `
Output Open your browser to http://localhost:3000/ . Y'all should at present see:
Congratulations! Yous did information technology!
Source: https://www.geeksforgeeks.org/upload-and-retrieve-image-on-mongodb-using-mongoose/
Post a Comment for "How to Create a Pdf Upload on Moongoose"