How to Upload a File From React to Express

In this tutorial, nosotros are going to learn about file uploading in React with using Express as a backend.

Creating Express Backend server

Outset, we are creating a mail API using NodeJS & express, which helps us to upload the files like (images, pdf, etc) to the backend server.

Setup the backend project

Allow's setup the node.js backend project by running the following commands one by one.

                          mkdir              fileupload              cd              fileupload              npm              init -y          

Installing packages

Now, we need to install four packages which are express, express-fileupload,cors and nodemon.

Run the below command to install packages.

                          npm              i express express-fileupload cors nodemon          

At present open the fileupload folder in your favorite lawmaking editor and create a new file called server.js.

Add the following lawmaking to the server.js file.

server.js

                          const              limited              =              require              (              'limited'              )              ;              const              fileUpload              =              require              (              'express-fileupload'              )              ;              const              cors              =              require              (              'cors'              )              const              app              =              express              (              )              ;              // centre ware              app.              employ              (limited.              static              (              'public'              )              )              ;              //to admission the files in public folder              app.              use              (              cors              (              )              )              ;              // it enables all cors requests              app.              use              (              fileUpload              (              )              )              ;              // file upload api              app.              post              (              '/upload'              ,              (              req,                res              )              =>              {              if              (              !req.files)              {              return              res.              status              (              500              )              .              send              (              {              msg:              "file is not constitute"              }              )              }              // accessing the file              const              myFile              =              req.files.file;              //  mv() method places the file inside public directory              myFile.              mv              (                              `                                  ${__dirname}                                /public/                                  ${myFile.name}                                `                            ,              function              (              err              )              {              if              (err)              {              console.              log              (err)              render              res.              status              (              500              )              .              transport              (              {              msg:              "Mistake occured"              }              )              ;              }              // returing the response with file path and name              return              res.              send              (              {proper noun:              myFile.name,              path:                              `                /                                  ${myFile.name}                                `                            }              )              ;              }              )              ;              }              )              app.              listen              (              4500              ,              (              )              =>              {              console.              log              (              'server is running at port 4500'              )              ;              }              )                      

In the to a higher place code, we first imported iii packages which are express, express-fileupload and cors, next we created limited awarding past invoking limited() function.

Our post API route is /upload.

We are placing files within the public binder and then that we demand to create a public folder inside our backend projection.

Calculation scripts

To run and restarting the server we are using the nodemon, open your package.json file and add the following code to scripts object.

                          "server"              :              "nodemon server.js"                      

Now start the backend server past running npm start server command in your terminal.

Creating React App

Let'due south create the new react app by running the following command.

            npx create-react-app react-fileupload          

Now change your electric current working directory by running the beneath command.

Installing Axios library

We also need to install the axios http client library which is used to make the http requests.

Creating file upload component

Open the react-fileupload binder in your favorite code editor and create a new file called fileupload.js inside the src folder.

Now add the post-obit code.

fileupload.js

                          import              React,              {              useRef,              useState              }              from              'react'              ;              import              axios              from              'axios'              ;              function              FileUpload              (              )              {                              const                [file,                setFile]                =                useState                (                ''                )                ;                // storing the uploaded file                            // storing the recived file from backend                              const                [data,                getFile]                =                useState                (                {                proper noun:                ""                ,                path:                ""                }                )                ;                            const              [progress,              setProgess]              =              useState              (              0              )              ;              // progess bar              const              el              =              useRef              (              )              ;              // accesing input chemical element              const              handleChange              =              (              e              )              =>              {              setProgess              (              0              )              const              file              =              east.target.files[              0              ]              ;              // accessing file              panel.              log              (file)              ;              setFile              (file)              ;              // storing file              }              const              uploadFile              =              (              )              =>              {                              const                formData                =                new                FormData                (                )                ;                            formData.              append              (              'file'              ,              file)              ;              // appending file              axios.              postal service              (              'http://localhost:4500/upload'              ,              formData,              {              onUploadProgress              :              (              ProgressEvent              )              =>              {              let              progress              =              Math.              round              (              ProgressEvent.loaded              /              ProgressEvent.total              *              100              )              +              '%'              ;              setProgess              (progress)              ;              }              }              )              .              then              (              res              =>              {              console.              log              (res)              ;              getFile              (              {              proper noun:              res.data.name,              path:              'http://localhost:4500'              +              res.data.path              }              )              }              )              .              catch              (              err              =>              console.              log              (err)              )              }              render              (              <div>              <div className=              "file-upload"              >                              <input type=                "file"                ref=                {el}                onChange=                {handleChange}                /                >                            <div className=              "progessBar"              mode=              {              {              width:              progress              }              }              >              {progress}              <              /div>                              <push onClick=                {uploadFile}                className=                "upbutton"                >                            Upload              <              /button>              <hr              /              >              {              /* displaying received image*/              }              {information.path              &&              <img src=              {data.path}              alt=              {data.name}              /              >              }              <              /div>              <              /div>              )              ;              }              consign              default              FileUpload;                      

In the above code, we accept used react hooks to manage the state and we have 2 functions which are handleChange and uploadFile.

The handleChange function is invoked once a user selected the file.

The uploadFile() function is used to upload the file to our /upload api.

There is also a progress bar, which shows the how much amount of file is uploaded to the server and also we are displaying the image once a response comes from the server.

Adding css styles

Add the following styles to your App.css file.

                          .App              {              margin              :              2rem automobile;              max-width              :              800px;              }              img              {              width              :              500px;              meridian              :              500px;              object-fit              :              contain;              }              .progessBar              {              top              :              1rem;              width              :              0%;              groundwork-colour              :              rgb              (68,              212,              231)              ;              color              :              white;              padding              :2px              }              .file-upload              {              box-shadow              :              2px 2px 2px 2px #ccc;              padding              :              2rem;              display              :              flex;              flex-direction              :              column;              justify-content              :              space-betwixt;              font-size              :              1rem;              }              input , div , button              {              margin-top              :              2rem;              }              .upbutton              {              width              :              5rem;              padding              :              .5rem;              background-colour              :              #2767e9;              color              :              aliceblue;              font-size              :              1rem;              cursor              :              pointer;              }                      

Now, import the FileUpload component inside the App.js file.

App.js

                          import              React              from              'react'              ;              import              FileUpload              from              './fileupload'              ;              import              './App.css'              ;              function              App              (              )              {              return              (              <div className=              "App"              >              <FileUpload              /              >              <              /div              >              )              ;              }              consign              default              App;                      

Showtime the react app by running npm start.

Testing react file upload component

Allow's test our FileUpload component past uploading a sample image file.

Note: Make certain that your backend server is on.

Open your browser and navigate to localhost:3000.

uploading image file demo

Code repositories

  • Backend server

  • React app

blackburnciontert.blogspot.com

Source: https://reactgo.com/react-file-upload/

0 Response to "How to Upload a File From React to Express"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel