Introduction

Here we will see how to download file from server using React JS framework. You can use any server side technology to download file but we will focus on client side technology React JS framework. You may read more on react here at https://reactjs.org/. We will provide link as well as button on which user will click and download file from server. User will get Save As option when clicks on download link or button.

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

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-download.

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-download 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-download 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 Download - React App</title>

Creating React Class – DownloadFile

Create DownloadFile.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 though in the below class we do not any variable that needs to be initialized. It is always good idea to call the super constructor even if we do not initialize any variable here.

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

Here the server URL sends JSON data which will be downloaded into a file.

We have two approaches in coding style for downloading the file and give users Save As option to save the file according to their choice of place.

We have the below code snippets that create URL with anchor tag, we pass the file name as employees.json and clicks on the URL to download the file with Save As option.

response.blob().then(blob => {
	let url = window.URL.createObjectURL(blob);
	let a = document.createElement('a');
	a.href = url;
	a.download = 'employees.json';
	a.click();
});

We have another line of code as shown blow, which will give users Save As option.

window.location.href = response.url;

You can use any one of the approaches to download file from server.

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

As we said in Introduction section that we will give users two options for downloading file using link or using button. So in this render() function we define our HTML elements with button and link to download file.

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

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

class DownloadFile extends React.Component {
	
	constructor(props) {
		super(props);
	}
	
	downloadEmployeeData = () => {
		fetch('http://localhost:8080/employees/download')
			.then(response => {
				response.blob().then(blob => {
					let url = window.URL.createObjectURL(blob);
					let a = document.createElement('a');
					a.href = url;
					a.download = 'employees.json';
					a.click();
				});
				//window.location.href = response.url;
		});
	}
	
	render() {
		return (
			<div id="container">
				<h1>Download File using React App</h1>
				<h3>Download Employee Data using Button</h3>
				<button onClick={this.downloadEmployeeData}>Download</button>
				<p/>
				<h3>Download Employee Data using Link</h3>
				<a href="#" onClick={this.downloadEmployeeData}>Download</a>
			</div>
		)
	}

}

export default DownloadFile;

Export the DownloadFile at the end of the DownloadFile 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 – download.css

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

The download.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 DownloadFile class. To import a class you must first have to export it as we did for DownloadFile in the last line.

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

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

ReactDOM.render(<DownloadFile />, 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:

download file

File – Save As

When you click any one of the download options – link or button, then you will see below output on the browser. You can choose any location to save your file.

download file using react

File – Employee Data

The saved file contains the below employee data when opened.

[{"id":1,"name":"Soumitra","email":"[email protected]"},{"id":2,"name":"Liton","email":"[email protected]"},{"id":3,"name":"Suman","email":"[email protected]"},{"id":4,"name":"Debabrata","email":"[email protected]"}]

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

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

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 *