Download file from backend API with React
If you have an endpoint in your API which delivers a file like text/csv; charset=UTF-8
and you want to let your user download this file, read on.
To make it easier for downloading files, I use the FileSaver library.
You can create these ‘Save As’ functions as this one:
Install it with:
npm install file-saver --save #or yarn add file-saver
Next, create the function which will make the request to the API.
// file /src/api/file.js
export const getDownloadFile = async () => {
return axios.get('/file.csv', {
responseType: 'blob',
})
.then(response => response.blob())
}
Then create, for example, a button which will let the user download the file
// file /src/pages/DownloadPage.js
import { getDownloadFile } from '../api/file'
import { saveAs } from 'file-saver'
...
export const DownloadPage = () => {
const downloadFile = () => {
getDownloadFile()
.then(blob => saveAs(blob, 'file.csv'))
}
return (
<button type='button' onClick={downloadFile}>Download</Button>
)
}