Skip to content

Instantly share code, notes, and snippets.

@jbutko
Last active June 12, 2024 08:12
Show Gist options
  • Save jbutko/d7b992086634a94e84b6a3e526336da3 to your computer and use it in GitHub Desktop.
Save jbutko/d7b992086634a94e84b6a3e526336da3 to your computer and use it in GitHub Desktop.
React, JS, Axios: Download blob file (PDF...)
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;
// }
};
@RTAndrew
Copy link

Thank you. It was really helpful. ♥️

@leocxy
Copy link

leocxy commented Nov 18, 2021

Thank you. It is working fine

@AnurajRicky
Copy link

how can I add a cancel action after the link click initiated?

@orendaeko
Copy link

orendaeko commented Feb 7, 2022

hi guys, have any of u already try to render blob on react component? not use window.open
thanks all

@fariasmateuss
Copy link

Nice work. Thank you.

@ali7sa
Copy link

ali7sa commented May 12, 2022

how do I use this code?

@zinchenko39
Copy link

The best! Thx!!!!

@fukemy
Copy link

fukemy commented Jan 31, 2024

where getProp plz, I am using react native

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment