Upload And Download File In Node
Here we will use multer middleware for uploading file. Click the link to know what is multer.
Setup The Project Folder
Setup The Project Folder
- create a new folder using console/terminal.
- open console/terminal type mkdir followed by the folder name you want to give.
- change to that folder by typing cd folder name.
- the npm init will create a package.json file.But we can create it manually too.
- just open the folder and add a new file and name it package.json and then we can structure it the same way as its been structured when using npm init.
- the package.json will look like this.
- now we will install packages for our project using npm install followed by package names we want to install.
- the following packages will be installed express ejs body-parser multer mongoose.
- this will generate a folder name node_modules which will contain all the node packages.
- after the package installation the package.json will look like this.
- now add a new file named it app.js.
- now go back to package.json file and in scripts write start :app.js.
- this will be the application entry point.
- make new folders 1) views and 2) public.
- in views add a file home.ejs.
- here we using .ejs extension for views file because the template engine we are using is ejs.
- now in public folder make a new folder uploads.
- the uploaded files will be stored in the uploads folder.
app.js
- mongoose.connect() - will setup the connection with local db on our system.
- localhost:27017/pics - pics is name of our database which will be created on server when we insert data in it.
- app.set("views",path.resolve(__dirname,"views")) - this tell express where views folder is.
- app.set("view engine","ejs") - this tells express that any file ending in .ejs should be rendered with ejs packages..
- express.static() - to serve static files such as images, CSS files, and JavaScript files, we using this middleware function.
- bodyParser - for fetching form data from the coming request.
- mongoose.Schema({}) - it contains the fields of our collection(table).
- mongoose.model() - it contains collection(table) name and the object containing collection(table) the field data.
- upload.single('pic') - in this we have to provide the same name of the name attribute which we used to upload the file.pic is the same name which is given in the name attribute . <input type="file"name="pic">.
- home.ejs
Comments
Post a Comment