Download file from server using React 16/17

Table of Contents

Introduction

Here I 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/. I 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.

Related Posts:

Prerequisites

React, Node v12.9.0/v14.15.5, npm 6.10.2/6.14.11, React 16/17

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

Project Setup

Go through the link https://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.

Change 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>

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

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

I have defined 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.

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

I 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();
});

I 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 you can use this class in other modules, such as, I have used it later in below index.js file.

Style – download.css

Notice I had included download.css style file into the above file but I didn’t say anything about it earlier. 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.

For React 16, the code looks similar to the below:

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();

For React 17, the code looks similar to the below:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';

import DownloadFile from './DownloadFile';

ReactDOM.render(
  <React.StrictMode>
    <DownloadFile />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Enough coding! Let’s make your 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 from server using react

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":"soumitra@email.com"},{"id":2,"name":"Liton","email":"liton@email.com"},{"id":3,"name":"Suman","email":"suman@email.com"},{"id":4,"name":"Debabrata","email":"debabrata@email.com"}]

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

source code

2 thoughts on “Download file from server using React 16/17

Leave a Reply

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