Last active
September 19, 2024 14:28
-
-
Save jbutko/d7b992086634a94e84b6a3e526336da3 to your computer and use it in GitHub Desktop.
React, JS, Axios: Download blob file (PDF...)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios, { AxiosResponse } from 'axios'; | |
import { get } from 'lodash-es'; | |
const rest = axios.create({ | |
baseURL: 'some base URL goes here', | |
}); | |
// this one send file as Blob type | |
const getPdf = () => ( | |
rest.get(`/get-pdf`, { | |
params: { | |
cacheBustTimestamp: Date.now(), // prevents IE cache problems on re-download | |
}, | |
responseType: 'blob', | |
timeout: 120, | |
headers: { | |
Accept: 'application/octet-stream', | |
}, | |
}) | |
); | |
export const downloadFile = async (response/*: AxiosResponse*/, filename/*: string*/ = 'download') => { | |
const data = get(response, 'payload.data', null) || getProp(response, 'data', null); | |
if (!(data instanceof Blob)) return; | |
const blob = new Blob([data], { type: 'application/pdf' }); | |
const link = document.createElement('a'); | |
link.href = window.URL.createObjectURL(blob); | |
link.download = `${filename}-${+new Date()}.pdf`; | |
link.click(); | |
window.URL.revokeObjectURL(link.href); | |
}; | |
export const openFileInNewTab = async (response/*: AxiosResponse*/, filename/*: string*/ = 'download') => { | |
const data = getProp(response, 'payload.data', null) || getProp(response, 'data', null); | |
if (!(data instanceof Blob)) return; | |
const blob = new Blob([data], { type: 'application/pdf' }); | |
// IE | |
if (window.navigator && window.navigator.msSaveOrOpenBlob) { | |
window.navigator.msSaveOrOpenBlob(data, filename); | |
return; | |
} | |
// Chrome, FF | |
const fileUrl = URL.createObjectURL(blob); | |
const w = window.open(fileUrl, '_blank'); | |
w && w.focus(); | |
// if you want to support Safari & Opera iOS version | |
// if (navigator.userAgent.indexOf('Chrome') != -1 || navigator.userAgent.indexOf('Firefox') != -1) { | |
// const w = window.open(fileUrl, '_blank'); | |
// w && w.focus(); | |
// } else { | |
// // Safari & Opera iOS | |
// window.location.href = fileUrl; | |
// } | |
}; |
how can I add a cancel action after the link click initiated?
hi guys, have any of u already try to render blob on react component? not use window.open
thanks all
Nice work. Thank you.
how do I use this code?
The best! Thx!!!!
where getProp plz, I am using react native
nice incorporation
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you. It is working fine