Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn
George Anderson
Frontend and backend development guru, lover of all things computer... and cats! Hopes to make your coder life a breeze by sharing some tips and tricks of the trade.
File upload is a very important feature of web applications: it helps facilitate actions like setting a user’s profile picture, setting up dynamic galleries, remote file storage, and file sharing, among many other functionalities. In this article, we will be looking at file upload (more specifically, images), using React web framework, to a Node.js Express backend server.

Here is the application we are going to be building: 
demo image upload in reactjs

Configuring Our React Development Environment

We’re going to use Eclipse and CodeMix to develop our React application. To install CodeMix into your Eclipse environment, please follow the installation instructions on this page.

Power up your React development with CodeMix, with superlative IntelliSense, validation, debugging and more! Get this Eclipse plugin that will also let you add all the VS code smarts and Code OSS extensions without leaving your preferred environment

So let’s get started with the React file uploads tutorial. Before proceeding, you have to make sure you have Node and npm (or Yarn) installed on your computer. If you don’t have them installed, you can download Node (which comes with npm) from the Node official website and follow the installation instructions.

Also, make sure that react-scripts is installed globally. This can be installed by executing the following command in the terminal:

 
Now we can create our project using Eclipse IDE by navigating to File > New > Project. Select the React option under the CodeMix list of projects, name the application and click Next to proceed (make sure you’re connected to the Internet to get the newest React template and folder structure for the application).  
 
Creating a React project in CodeMix

Creating a React project in CodeMix

Once the process is completed, we can now install the required dependencies for our project using Ctrl+Shift+P to open a command terminal. Once the terminal is opened, execute the command below to install all the required packages:
Afterwards, we will pull in some modules we would use to build the application, using the command below:
 

Development

Before we get started with coding, let’s go over a few of the technologies we will be using:

  • Express: it is a Node.js module which simplifies the creation of a node server.
  • Cors: it is a Node.js module that provides a middleware to handle cross-origin resource sharing.
  • Multer: it is a Node.js middleware for handling “multipart/form-data”, which is primarily used for uploading files.
  • Axios: it is a Promise-based HTTP client which we will use to communicate with the Node server.

Let’s move on to the development of the application. First, we would create the server that would have just one route, which would accept the files submitted, save them and return a path to the files. We do this by creating a file at the root of our project folder called server.js, which contains the server setup, Multer configuration and the sole route of the application.

This file should look like this:

The first section of this code loads all modules we would be using in setting up our Express backend. It also instructs Express to load all files in the public directory in root directory of the project (that is, it exposes them to be rendered through call to the file path from the root URL).

Next, we set up the configuration for the multer middleware, telling multer how and where to store received files. In our case, we are saving them in the public/images/uploads directory. Then we instantiate a multer object, passing to it the configuration which we created.

Afterwards, we create the route to which the image will be posted (This is done after we enabled the cors middleware.). On the route definition, we pass the multer middleware which expects a single file upload. We then return the file path as response data to the caller or return an error if no file is found.
 
We then run the server on the given port. To run the server, we have to include an entry in the package.json file in the scripts array. 
This will enable us to run the server from the terminal, using the following command in the project directory. After that, we can proceed to build our React application to use the server we created.

We proceed by creating a file app.js which would contain our application’s main component. 

Given the template provided by CodeMix, we would have an index.js which is the entry point the application. Here we will import our App component and render it.

Code Completion in CodeMix

The index.js should look like this:

Now we can proceed to implement the React part of this application. The app.js file should contain the code below:
In the constructor, we initialize the state object of the component. Next, we define the selectImages method which is triggered by the onChange event of the file input field. Here we loop through the FileList object received from the input field, validating and checking to make sure that the files are images (using a property on each file called “name” in a regular expression match check) and adding the result to the images property on the state object. 
 
Next, we define the uploadImages which is triggered by the onClick event on the submit button. This method loops through the images array in the component state (creating a form containing the next image to be uploaded), sends them as post request using axios to the upload URL and, finally, saves each file URL received to the imageUrls array in the state. We then handle the event of completion of all uploads using the axios.all method on the array of promises returned to the uploaders handle.
 
Finally, we render each of the images uploaded, using the array of file paths in the imageUrls object in the state object.
 

Conclusion

In this article, we discussed how to create a Node Express backend that accepts file inputs, stores the file, and returns the path to the file for rendering. We also covered interaction with a server which we created using the React framework. The method used performs adequately for both single and multiple file (image) uploads.
 
We also took advantage of the various features presented to us by CodeMix, including application scaffolding, syntax highlighting, and code snippets throughout the development of this application.
 
The code for this application can be downloaded here.

Related Posts

React Tutorial: Create and Debug an App in Eclipse... Making React run properly in Eclipse can be a really big headache…or an amazingly cool experience with CodeMix! CodeMix integrates the best of the VS Code world into Eclipse, such as support to create and debug React applications. Follow this React tutorial to quickly create and debug an app in Eclipse with CodeMix:Create Your App Make sure you hav...
The CodeMix Journey The CodeMix JourneyThanks for joining us on the CodeMix journey! We are thrilled to announce the release of CodeMix 2.0. With this release, CodeMix exits the technical preview phase. We are especially grateful to all of the Insiders whose feedback has helped us fine-tune CodeMix to be a truly outstanding companion to your Eclipse IDE, bringing you ...
A Day with Dani: Digging in for Some Coding "Become a programmer!" - this has been my dream ever since I realized the pivotal role developing has in creating new technologies that could change the world and positively impact those around me. My name is Danielle and I am the summer intern at Genuitec! I am going on to my fourth week here and am so excited to start sharing my personal thoughts...
Angular Elements Made Simple with CodeMix Angular has been one of the best front-end JavaScript frameworks for some time now, and one of the many reasons is their continued effort to bring to developers new and improved ways to get the job done. One such effort is Angular Elements, which were introduced in Angular v6. In a nutshell, they convert components to HTML elements (+ JavaScript), ...

Posted on Aug 30th 2018