Introduction

In this post we will see how to upload file to server using React JS framework. In server side you can use any server side technology for implementing REST API that will store file into a physical path or persistence storage. Here we will only focus on client side technology React framework only. user will be provided a browse button to select a file and a button for uploading file into server. The button will be disabled by default until a user selects a file for uploading.

You may also like to read How to download file from server using React.

Prerequisites

React 16.8.6, Node v11.3.0, npm 6.4.1

Example with Source Code

Go through the following steps for creating React project to download file from server using React.

Creating Project

Go through the link https://www.roytuts.com/react-application-windows/ to create new React JS project. make sure to give the project name as react-file-upload.

Wait till the project directory creation is not finished. When done you will get successful message.

Make sure you check the application runs at http://localhost:3000/ by executing npm start on project directory react-file-upload using cmd prompt.

Note that when we open a file or edit a file in subsequent sections we will by default refer to the project root directory react-file-upload and later we may not mention this directory name.

Changing the Title

When project directory creation is finished with all of its components then first task is to change the default title of the page.

Open the file public/index.html and update the title tag as shown below:

<title>File Upload Example - React App</title>

Creating React Class – UploadFile

Create UploadFile.js file under src directory with below content. Notice that you need to import the required module or component such as import React from ‘react’.

We should initialize variable’s state in constructor in the below class. It is always good idea to call the super constructor even if we do not initialize any variable here.

We have two property of the class – file and msg. The file property holds the selected file and msg property sets any available message.

We have a function onFileChange() that checks whether a file has been selected or not for upload and accordingly disables or enables the upload button.

We define a function called uploadFileData() that will call REST API URL, for example, http://localhost:8080/upload and this REST API could be implemented using any server side technology as per your requirement.

Here the server URL uploads the file data.

We create a new form and append the file data into request body with a parameter file.

On file upload success we display the success message to the end user.

Next we have render() function to render the elements of React app. Elements are the building blocks of React apps.

So in this render() function we define our HTML elements with button and link to download file.

The uploadFileData() function is called on onClick() function (onclick event of JavaScript).

import React from 'react';
import './upload.css';

class UploadFile extends React.Component {
	
	constructor(props) {
		super(props);
		this.state = {file: '', msg: ''};
	}
	
	onFileChange = (event) => {
		this.setState({
			file: event.target.files[0]
		});
	}
	
	uploadFileData = (event) => {
		event.preventDefault();
		this.setState({msg: ''});

		let data = new FormData();
		data.append('file', this.state.file);

		fetch('http://localhost:8080/upload', {
			method: 'POST',
			body: data
		}).then(response => {
			this.setState({msg: "File successfully uploaded"});
		}).catch(err => {
			this.setState({error: err});
		});

	}
	
	render() {
		return (
			<div id="container">
				<h1>File Upload Example using React</h1>
				<h3>Upload a File</h3>
				<h4>{this.state.msg}</h4>
				<input onChange={this.onFileChange} type="file"></input>
				<button disabled={!this.state.file} onClick={this.uploadFileData}>Upload</button>
			</div>
		)
	}

}

export default UploadFile;

Export the UploadFile at the end of the UploadFile class so that we can use this class in other modules, such as, we have used it later in below index.js file.

Applying Style – upload.css

Notice we had included upload.css style file into the above file but we didn’t say anything about it. This file is put under the src directory.

The upload.css file contains simple style to for the div with id container and defines the width of the div with auto margin.

#container {
	width: 800px;
	margin: auto;
}

Updating index.js

Update the index.js file under src directory to import the UploadFile class. To import a class you must first have to export it as we did for UploadFile in the last line.

Notice how we render the React elements using render() from UploadFile into a div called root, which is present on the public/index.html file.

import React from 'react';
import ReactDOM from 'react-dom';
import UploadFile from './UploadFile';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<UploadFile />, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

Enough coding! Let’s make our application runnable and testable.

Testing the Application

If you didn’t run the command npm start on your project root directory from cmd prompt then you can execute this command. The application will start at http://localhost:3000 and open in a default browser.

Home Page

The home page of the application looks to the similar image as shown below:

upload file to server using react js

File – Selection

When you select a file using browse button:

upload file to server using react js

File – Upload Success

When file successfully uploaded to the server:

upload file to server using react js

For server side code using Spring Boot you can use Upload file using React and Spring Boot.

Source Code

You can download source code.

Thanks for reading.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *