How to download a zip file in React.js?

by tressie.damore , in category: Javascript , a year ago

How to download a zip file in React.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 10 months ago

@tressie.damore 

In React.js, you can use the fetch API or a library like axios to download a zip file. Here's an example of how you can download a zip file in React.js:

  1. Install axios (if you don't have it already) by running npm install axios or yarn add axios in your project directory.
  2. Import the necessary dependencies:
1
import axios from 'axios';


  1. Create a function to handle the download:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
const handleDownload = () => {
  axios({
    url: 'https://example.com/path/to/your/zip/file.zip',
    method: 'GET',
    responseType: 'blob', // important
  }).then((response) => {
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'file.zip'); // specify the filename
    document.body.appendChild(link);
    link.click();
  });
};


  1. Use the handleDownload function when triggering the download, for example, in a button click event:
1
<button onClick={handleDownload}>Download Zip</button>


Make sure to replace 'https://example.com/path/to/your/zip/file.zip' with the actual URL of the zip file you want to download.


This code makes a GET request to the specified URL, receives the zip file data as a blob, creates a download link element, and triggers a click event on it to initiate the download with the specified filename.