Hello Friends,
Welcome To Infinitbility!
This article based on how to download any file in react, when you are working any type of project there are one definitely feature is download report.
May be you are looking for excel ( xslx, and csv ), pdf, video ( mp4, mov, and avi ), image (png, jpg, and jpeg ) and etc but in this article we will learn to download any type file in react.
Let start today article How to download file in react
For download any type of file we will need two react packages
- axios - https://github.com/axios/axios
- js-file-download - https://github.com/kennethjiang/js-file-download
We will use axios for fetch file url and js-file-download for make fetch data downloadable.
Installation
You have to first install both package using below command on your project.
Install axios
npm install axios
Install js-file-download
npm install js-file-download --save
Usages
Using axios and js-file-download you can download any file in any browser.
Let’s understand with example
import fileDownload from 'js-file-download'
import axios from 'axios'
let filePath = “https://example.com/filename.csv”;
axios.get(`${filePath}`, {
responseType: 'blob',
}).then((res) => {
let filename = filePath.replace(/^.*[\\\/]/, '')
let fileExtension;
fileExtension= filePath.split('.');
fileExtension =fileExtension[fileExtension.length -1];
fileDownload(res.data, `${filename}.${fileExtension}`);
});
Thanks for reading…