node example to upload files and see details

Whenever we submit a form on the client-side of any website, all the course data goes to the server-side. Usually, grade-data gets encoded before we submit it to the server. We can do this by specifying the enctype attribute in the <form> tag in HTML. If we don't specify it, form-data gets encoded with the default type.

Introduction

This is usually the case when we are dealing with text-simply information like proper name, email, and password, etc.

But, if we are uploading some kind of files, we need to specify the enctype aspect with the value multipart/form-data. This value is required when we are using forms that have a file input type element.

Multer is an npm package that makes it easy to handle file uploads. It does it very efficiently, thus it is quite pop. In this commodity, we will see how to use Multer to handle multipart/grade-data using Node.js, Limited and MongoDB.

Prerequisites

There are 4 things y'all should know/have installed before you attempt this tutorial.

  1. Practiced agreement of HTML and CSS.

  2. Node.js should be installed in your organization and you should take a working knowledge of it.

  3. MongoDB should exist installed in your organization and you should take a working knowledge of it.

  4. Expert understanding of the command-line or integrated terminals in code-editors.

Goals of the tutorial

The goal of this tutorial is to aid yous understand these iv things:

  1. How to pattern an API endpoint for posting data.

  2. How to utilise Multer as a middleware for that API.

  3. How to manage and store those files on the server-side.

  4. How to view those files on the front-end.

Project setup

Starting time, create a new folder/directory in your organisation and name it Multer-Tutorial. And then, open this binder in your favorite code editor. I'll be using VSCode.

Next, create a new HTML file and name information technology index.html. Inside information technology, nosotros volition add a class to upload files. Your HTML lawmaking should wait something like this:

                          <!DOCTYPE html>              <html              lang              =              "en">   <head>     <meta              charset              =              "UTF-8"              />     <meta              name              =              "viewport"              content              =              "width=device-width, initial-scale=1.0"              />     <link              href              =              "https://fonts.googleapis.com/css2?family=Lato:wght@100;400;700;900&display=swap"              rel              =              "stylesheet"              />     <link              href              =              "https://stackpath.bootstrapcdn.com/font-crawly/4.7.0/css/font-awesome.min.css"              rel              =              "stylesheet"              integrity              =              "sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN"              crossorigin              =              "anonymous"              />              <!-- fashion.css file path in the line below. -->              <link              rel              =              "stylesheet"              href              =              "css/mode.css"              />              <!-- -------------------------------------- -->              <championship>Multer Tutorial</title>   </head>   <body>     <primary              grade              =              "admin">       <div              form              =              "admin__upload-file">         <class              activity              =              "#"              enctype              =              "multipart/form-information"              method              =              "mail">           <input              type              =              "file"              class              =              "admin__input"              id              =              "myFile"              proper name              =              "myFile"              />           <input              form              =              "admin__submit"              type              =              "submit"              />         </form>       </div>     </primary>   </trunk> </html>                      

Important points to notation in the code above

  • In the form tag, the enctype attribute must exist prepare to multipart/class-data, for Multer to work.

  • Also, in the grade tag, nosotros take specified the activity attribute to #. This is because nosotros haven't made any API endpoint to receive the data from this form. Nosotros'll be creating this API endpoint after in this tutorial.

Note: The header links in the HTML lawmaking is my personal way of styling. You lot can mode this page as you want and don't forget to write your CSS in the way.css file created inside the CSS binder in the root directory. I will share my CSS code at the end of this tutorial because this article focuses on using Multer.

You should follow the same folder structure that's specified. I'll be sharing information technology several times every bit we create new files and folders so you can follow this tutorial without any difficulty.

Electric current binder construction

Multer-Tutorial (Root Directory)

alphabetize.html (file) css (folder)

style.css (file)

Next steps

Before moving forward, brand sure that Node.js is installed in your organisation. Write this command in your final to bank check whether it is installed.

It should show you the installed version of Node.js in your system.

Something like:- v14.8.0

Now, since our static site is ready we tin start initiating this project with npm. To do this:-

  • Write this command in the integrated terminal in your code editor or in any command line tool. Make sure that yous are in the root directory of this project while running this command.

npm init -y creates a new bundle.json file. This file will help united states of america to manage all the dependencies that nosotros will install afterwards in this tutorial only you should create the master pick in parcel.json from index.js to app.js.

The resulting package.json file should look like this:

package.json

Setting up the project with Node.js, Express, and MongoDB

First, we need to install the three most important npm packages that we need for this tutorial.

These are: express, body-parser and mongoose.

Thus, write this command in the terminal:

            npm i express body-parser mongoose                      
  1. Express will help the states create different API endpoints and much more.

  2. torso-parser will mount the data coming from the course onto the incoming request.

  3. Mongoose will help usa piece of work with MongoDB easily.

Let's start by creating a new file named app.js in our root directory. In this file, we will make different routes and besides write some configuration code.

Write the following lawmaking in your app.js file.

                          // Calling all the required packages                                          const              express              =              require("express");              const              bodyParser              =              require("trunk-parser");              const              app              =              limited();              // Configurations for "body-parser"                                          app.use(              bodyParser.urlencoded({              extended              :              true,   }) );              // Configurations for setting up ejs engine &                            // displaying static files from "public" binder                            // TO Be ADDED LATER                                          // Routes volition be added hither later on                                          //Express server                                          module.exports              =              app;                      

Note that I have exported the app because we will be creating a new file. In that file, we will make our express server and a connectedness with our MongoDB cluster.

Please refer to these two videos to learn how to make a MongoDB cluster in Atlas (cloud database) and how to connect information technology to our project.

  1. This video will help yous create a cluster.

  2. This video will help y'all connect it to our projection.

When you are set with your cluster, create a new file in the root directory and name it server.js. This file will make the connection with our server and database.

Write this code in the file:

                          const              app              =              require("./app");              const              mongoose              =              crave("mongoose");              process.on("uncaughtException", (err) => {              console.log("UNCAUGHT EXCEPTION, APP SHUTTING NOW!!");              console.log(err.message,              err.name);              process.get out(1); });              const              DB              =              "ENTER YOUR Connexion STRING Here";              mongoose              .connect(DB, {              useCreateIndex              :              true,              useFindAndModify              :              truthful,              useNewUrlParser              :              truthful,              useUnifiedTopology              :              true,              autoIndex              :              true,   })   .and so(() => {              console.log("DB connected successfully");   });              const              port              =              3000;              const              server              =              app.listen(port, () => {              panel.log("Server is up listening on port:"              +              port); });                      

Don't forget to enter your connection URI string in the DB variable.

Now, we have to run our project on the express server that we have mentioned. To exercise this, run the "server.js" file by writing this command on the terminal.

You lot should see this message on the concluding if you lot have done everything right:

            Server is up listening on port:3000 DB connected successfully                      

If y'all run into something else like any mistake, spotter those videos again or try fixing those errors by surfing on the internet.

Before writing any code in the app.js file, we take to make some new folders and change the locations of some files. You must be wondering why we are putting and so much attempt into emphasizing these things.

Information technology is because writing clean and manageable code with an organized folder structure is as important as writing the "correct" code. These kinds of folder construction and refactoring will help you with your big, futurity projects.

  • Create a new binder in the root directory and proper name information technology public. This will concord the static files that nosotros will serve. Cut the css folder that we created at the start of this project and paste it into this folder.

  • Create a second binder and name it views. This will agree our HTML file that we created at the commencement.

Since we are dealing with a HTML file, nosotros have to make some changes. First, change the file extension from .html to .ejs because we'll exist using the ejs render engine. And so, inside the caput tag, where we have linked our CSS file, change that link from this:

            <link              rel              =              "stylesheet"              href              =              "css/style.css"              />                      

to this:-

            <link              rel              =              "stylesheet"              href              =              "/css/mode.css"              />                      

We accept added the '/' in front of it considering nosotros now accept to mention the relative path from the public binder, equally it contains our static files.

New folder structure

├───node_modules (binder)
├───public (binder)
│ └───css (folder)
|──────└───way.css (file)
|───views (folder)
│────└───index.ejs (file)
├───app.js (file)
├───packet-lock.json (file)
├───packet.json (file)
├───server.js (file)

Nosotros have to define some routes in our app.js file, and then we will start by defining the route for our abode page.

Follow these steps:

  • Install the template engine for ejs by writing this command:
  • Include the path package at the top which is a built-in Ndde.js parcel.
                          const              path              =              require("path");                      
  • Write the configuration lawmaking for setting upwards the EJS template engine and defining the path.
                          app.set("view engine",              "ejs");              app.set("views",              path.join(__dirname,              "views"));              app.use(express.static(`              ${              __dirname              }              /public`));                      
  • Now, we volition create our first API endpoint, to return the HTML file that we build at the start of this tutorial.
                          app.use("/", (req,              res) => {              res.status(200).return("index"); });                      

After all these steps, your app.js file should await like this.

app.js

Restart the server with the same command as above:

Y'all should run into the rendered HTML file that you created before.

Uploading and storing files

Before using Multer to handle the upload action of files, we need to understand a few things.

  • The actual files are never stored in the database. They are e'er stored someplace on the server. In our tutorial, we will store the uploaded files in the public folder.

This is because all the files that are in the public folder are meant to be available to the public at the front end-end.

Later in the tutorial, we volition learn how to view those files on the front-end. And so, that is some other reason to store them in the public folder.

  • Just, we will use the database to store some information near those files. The commencement thing can be the name of the file and other data can vary co-ordinate to the project.

Next nosotros create a schema to store the name of our uploaded files. We will do this with the help of the Mongoose package that we installed earlier.

To do this, follow these three steps:

  1. Create a new folder and proper name it model.

  2. Create a new file in it and name it the `fileSchema.js``.

  3. Write this lawmaking in that file.

                          // Calling the "mongoose" package                                          const              mongoose              =              require("mongoose");              // Creating a Schema for uploaded files                                          const              fileSchema              =              new              mongoose.Schema({              createdAt              :              {              type              :              Date,              default              :              Date.at present,   },              name              :              {              type              :              String,              required              :              [truthful,              "Uploaded file must have a name"],   }, });              // Creating a Model from that Schema                                          const              File              =              mongoose.model("File",              fileSchema);              // Exporting the Model to utilize information technology in app.js File.                                          module.exports              =              File;                      

This is how we create a Schema with Mongoose and extract a model from it. We will now use this model to store data about uploaded files in MongoDB. Don't forget to call this model in the app.js file at the top.

                          const              File              =              require("./model/fileSchema");                      

Next, create a new folder named "files" inside the public binder. This is where we'll be storing the uploaded files.

Updated binder structure:

├───model (folder)
│ └───fileSchema.js (file)
├───node_modules (folder)
├───public (folder)
│ └───css (folder), files(folder)
|──────└───style.css (file)
|───views (binder)
│────└───index.ejs (file)
├───app.js (file)
├───bundle-lock.json (file)
├───parcel.json (file)
├───server.js (file)

Multer

As mentioned previously, Multer is a Node.js middleware used for handling multipart/form-data, which is primarily used for uploading files.

For those who don't know what a middleware is in Node.js, it'south a part that receives the request and response object when a user from the client-side makes any asking.

There are ii uses of middleware in Node.js:

  1. To ship the response based on the request coming from the user.
  2. To change or modify the request object and send information technology to the adjacent middleware.

We tin add equally many middleware equally nosotros wish in this request-response bicycle. Let's start by installing Multer.

Write this control in your terminal:

Afterwards installing the bundle, we will import information technology at the top of the app.js file:

                          const              multer              =              crave("multer");                      

Then we will first past creating an API endpoint to upload the file, just higher up the previous one.

Notation: Make sure that the endpoint used to render the page is at the end of all the API endpoints.

                          //API Endpoint for uploading file                                          app.post("/api/uploadFile", (req,              res) => {              // Stuff to be added later                            });                      

Let's start using Multer

We are going to store the uploaded files in our deejay storage inside the files folder that we just created. Let's kickoff by defining the destination. Copy the post-obit code in your app.js file just below the code for configuration of static files.

                          //Configuration for Multer                                          const              upload              =              multer({              dest              :              "public/files"              });                      

In this code, we are calling the multer function that takes sure options equally arguments. Nosotros pass the dest (destination) option and the value of dest will be:public/files.

Later that, we have to employ this upload variable as the middleware in the API endpoint created to a higher place.

Change that API endpoint to this:

                          app.post("/api/uploadFile",              upload.single("myFile"), (req,              res) => {              // Stuff to be added later on                                          console.log(req.file); });                      

Hither, upload.single is again a role. The single determines that only a single file is to be uploaded. In the case of there being many files, nosotros tin can use multiple instead of unmarried.

Information technology takes a string as an argument and that cord is the name of the input that nosotros mentioned in our HTML code.

Nosotros did panel.log(req.file) to see the details of the file that we are uploading. This will assistance united states of america configure multer in a more advanced fashion. We will also be able to do the filtering on those files.

At present, we can starting time past sending the request with files on this API. But, before that, we need to make modest changes in our HTML code in the index.ejs file.

Open up that file and change the value of the action attribute in the form to '/api/uploadFile'. Also, note the name of the input that we mentioned in the higher up lawmaking.

            <form              action              =              "/api/uploadFile"              enctype              =              "multipart/form-data"              method              =              "POST">   <input              blazon              =              "file"              class              =              "admin__input"              id              =              "myFile"              name              =              "myFile"              />   <input              form              =              "admin__submit"              type              =              "submit"              /> </form>                      

Only to make sure that nosotros are on the same folio, here is the land of the app.js file upwards to now.

app.js

Finally, you tin upload a file from your rendered folio. You should encounter something like this on your final window when yous hit submit.

This is my output. Yours will be dissimilar based on what you uploaded.

                          {              fieldname:              'myFile',   originalname:              'Final Resume.pdf',   encoding:              '7bit',   mimetype:              'awarding/pdf',   destination:              'public/files',   filename:              '54a87baf681a51490eda5626f495df6c',   path:              'public\\files\\54a87baf681a51490eda5626f495df6c',   size:              2034370              }                      

Too, annotation that a new file would already take been created in your files folder under public. Just, that file won't exist readable considering there is no extension for that file.

With the information we just got, we will configure multer in a more complex way so that our files become readable.

Configuring Multer

At present, we tin start configuring Multer in a more circuitous manner and we will do that in two parts:

  1. Configuring the disk storage and naming the uploaded files.

To do this, supplant the previous one-liner code for configuration with this code:

Delete this:

                          //Configuration for Multer                                          const              upload              =              multer({              dest              :              "public/files"              });                      

Now write this:

                          //Configuration for Multer                                          const              multerStorage              =              multer.diskStorage({              destination              :              (req,              file,              cb) => {              cb(naught,              "public");   },              filename              :              (req,              file,              cb) => {              const              ext              =              file.mimetype.split("/")[1];              cb(null,              `files/admin-              ${              file.fieldname              }              -              ${Date.now()}              .              ${              ext              }              `);   }, });                      

Multer has an in-built method called diskStorage and it takes a couple of options. The first option is once more the destination, just we cannot but set up it as we did before.

The destination option is a callback function that takes three arguments:

  1. req, which is the incoming request object.

  2. file, which is the incoming file object (that we saw in the terminal a bit before).

  3. cb, which is again another callback function.

We call the cb function that takes the two arguments. The kickoff is error which we are going to pass null to. The second is the destination binder which is public.

The second option that this method takes is the filename. It is almost the same as the destination pick except in this, the inner callback function takes the filename as the second argument.

So, you lot can encounter that I have created a unique filename for this using the template cord in JavaScript. You tin refer to the file object that nosotros logged in to our terminal earlier. I take taken the extension from the mimetype property of the file object and besides the fieldname.

Congratulations. We have completed the first step of configuring Multer. Adjacent, we will brand a filter to filter out dissimilar kinds of files. I volition make a filter to but permit the upload of PDF files. You can make your ain filter past referring to the code below:

                          // Multer Filter                                          const              multerFilter              =              (req,              file,              cb) => {              if              (file.mimetype.carve up("/")[ane]              ===              "pdf") {              cb(aught,              true);   }              else              {              cb(new              Error("Not a PDF File!!"),              false);   } };                      

Now, this slice of code is very simple. Multer filter is just a function that as well has req, file, and a callback role as its arguments. In this, we volition check if the uploaded files are PDFs, if then nosotros will pass true in the callback role. If it isn't a PDF, we will pass imitation forth with an error in the callback function. If you lot desire to filter out another files similar images, y'all can exercise that easily by checking the mimetype of the uploaded files.

The last step is to again phone call the Multer part but now passing our manually configured multerStorage and multerFilter as options like the code below:

                          //Calling the "multer" Office                                          const              upload              =              multer({              storage              :              multerStorage,              fileFilter              :              multerFilter, });                      

Save the file to restart the server.

At present, if you endeavour to upload a PDF file, you should come across that uploaded file (in PDF format) in your files binder under the public directory. But, if y'all upload whatsoever other file, it volition show an error.

So, we can finally meet our uploaded file in our disk storage. Merely, if we want to run across this file on the front-cease, we need to store the name of the file in our database. Since, we take already created the schema for our database, all we have to exercise is to salve the name of the file in our route-handler part.

Write the post-obit code inside the uploadFile API endpoint:-

                          // Stuff to exist added later                            // console.log(req.file)                                          attempt              {              const              newFile              =              await              File.create({              name              :              req.file.filename,   });              res.status(200).json({              condition              :              "success",              bulletin              :              "File created successfully!!",   }); }              take hold of              (error) {              res.json({              error,   }); }                      

Updated app.js File

app.js3

Know if you lot upload a file and hit submit again, the proper name of the file will be saved in your cloud database. To see that, you can go to your cluster at the MongoDB site, and in the collections, you lot should see something like the image beneath:

atlas

Note that, the name of the file in the database should lucifer the filename in your disk storage and this is how we tin can upload a file using Multer as a middleware in a node.js application.

View these files on your front-cease

The next function of this tutorial is to view these uploaded files on the forepart-end of your project. To do this, we take to create another API endpoint to go all the files.

Write the following lawmaking in your app.js file:

                          app.get("/api/getFiles",              async              (req,              res) => {              effort              {              const              files              =              await              File.notice();              res.condition(200).json({              status              :              "success",              files,     });   }              catch              (error) {              res.json({              status              :              "Neglect",              error,     });   } });                      

Now, all we have to practise is make an API call on this endpoint. I prefer using Axios to do this. Afterwards getting the results, we tin show these files on our page using some basic HTML code and CSS.

Include this script at the end of your HTML code earlier closing the <html> tag.

            <script              src              =              "https://unpkg.com/axios/dist/axios.min.js"></script>                      

I'll include the JavaScript code later the HTML merely you can create a new JavaScript file and then identify it in the public directory the aforementioned every bit your CSS file.

            <script>              const              parentDiv              =              document.querySelector(".admin");   window.addEventListener("load",              async              () => {              try              {              let              outcome              =              await              axios({              method              :              "Become",              url              :              "/api/getFiles",       });              let              files              =              result.data.files;              files.forEach((file) => {              markup              =              `                                            <div grade="files__entity">                                            <i class="files__icon fa fa-file-text" aria-hidden="true"></i>                                            <span course="files__date">Date created:-                            ${              file.createdAt              }              </span>                                            <a href="              ${              file.name              }              " class="files__link"><i course="fa fa-eye tests__icon" aria-hidden="true"></i></a>                                            </div>                                            `;              parentDiv.insertAdjacentHTML("beforeend",              markup);       });     }              take hold of              (error) {              console.log(error);     }   }); </script>                      

With this code, we are calling the API endpoint that we created and with the data nosotros receive, we are making entities for each different file. We too made a link in those entities and set its value to the proper noun of the file stored in the database. This way, when we click that link, our uploaded file will open in our browser.

CSS Styles

                          *,              *::before              ,              *::later              {              margin:              0;              padding:              0;              box-sizing:              inherit; }              html              {              font-size:              62.5              %;   ringlet-behavior:              smooth; }  .admin              {              margin-left:              50              %;              margin-top:              7              rem;              transform: translateX(-xxx              %); }  .admin__input              {              edge:              none;              background-color:              #41398e;              padding:              1              rem              1.viii              rem;              color:              #e2e0e0;              border-radius:              10              rem;              margin-right:              2.5              rem; }  .admin__submit              {              border:              none;              background-color:              #603556;              padding:              1              rem              1.8              rem;              color:              #e2e0e0;              border-radius:              10              rem;              cursor:              pointer; }  .admin__submit:focus              {              outline:              none; }  .files__entity              {              background-color:              lightgray;              display:              inline              -              block;              padding:              five              px              10              px;              text-marshal:              center;              margin-superlative:              20              px;              font-size:              14              px; }                      

Conclusion

Congratulations. Y'all've uploaded files using Multer and viewed them on the front-end. In that location are likewise lots of things that nosotros tin can do with Multer, therefore I suggest you lot to check out its documentation here.

If y'all want to upload images, resize them according to your needs, in society to relieve space on the server. We would accept to shop the images in the buffer storage before storing them in disk storage.

Happy Coding!


Peer Review Contributions by: Peter Kayere

harperency1954.blogspot.com

Source: https://www.section.io/engineering-education/uploading-files-using-multer-nodejs/

0 Response to "node example to upload files and see details"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel