-
-
Save javilobo8/097c30a233786be52070986d8cdb1743 to your computer and use it in GitHub Desktop.
axios({ | |
url: 'http://localhost:5000/static/example.pdf', | |
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.pdf'); | |
document.body.appendChild(link); | |
link.click(); | |
}); |
Thanks a lot !
Many thanks, you saved my day
Thanks
Bless you!!!
Thank you!
This is the fix I've been looking for everywhere
Thanks for the solution.
Thanks for the solution 🥲
in a c# rest api what should my endpoint return for axios to take it as a valid "Blob"?
Thanks for the easy snippet & example 🤖
Thank you, saved my day!!! S2
it worked perfectly with vue.js
how to progress download?
how to progress download?
Maybe the Axios optiononDownloadProgress
or this package axios-progress-bar can help you
Thank you bro
Thank you for great solution!
How to do it in react-native?
try { const response = await axios.get(homeService.downloadPlan, { headers: { Authorization:
Bearer ${idToken}`,
hospitalId: arg.hospitalId,
},
params,
responseType: 'blob',
});
// Save the PDF file to the device's storage
const { dirs } = RNFetchBlob.fs;
console.log('RN', dirs.DownloadDir);
// file name
const pdfFileName = `${arg.code}_${arg.plan}.pdf`;
const fileUri = `${dirs.DownloadDir}/${pdfFileName}`;
const pdfData = response.data;
console.log('response ', pdfData);
try {
await RNFS.writeFile(fileUri, pdfData);
console.log('Saved at :', fileUri);
} catch (error) {
console.log('Error saving file:', error);
}
return response;
} catch (error) {
throw new Error('API Error');
}`
above code saves the file as pdf with 8 blank pages size of file and no of pages are correct.
thanks
This is great. Thanks
Using
responseType: 'blob'
Axios returns a blob, you don't need to convert it into a blob again.axios({ url: 'http://localhost:5000/static/example.pdf', method: 'GET', responseType: 'blob', // important }).then((response) => { const url = window.URL.createObjectURL(response.data)); const link = document.createElement('a'); link.href = url; link.setAttribute('download', 'file.pdf'); document.body.appendChild(link); link.click(); });And using
FileSaver
you can save some lines of code increasing the browsers compatibility:import { saveAs } from 'file-saver' axios({ url: 'http://localhost:5000/static/example.pdf', method: 'GET', responseType: 'blob', // important }).then((response) => { saveAs(response.data, 'file.pdf'); });
Asking axios to return a blob instead of returning text and building a blob saved me days of banging my head on the desk.
Was constantly seeing corrupted data and couldn't figure out why. The file-saver
package made my code a ton cleaner as well.
Thank you so, so much @sergiop!!!
Очень здорово! Спасибо большое!