Skip to content

Instantly share code, notes, and snippets.

@javilobo8
Last active May 13, 2025 05:55
Show Gist options
  • Select an option

  • Save javilobo8/097c30a233786be52070986d8cdb1743 to your computer and use it in GitHub Desktop.

Select an option

Save javilobo8/097c30a233786be52070986d8cdb1743 to your computer and use it in GitHub Desktop.
Download files with AJAX (axios)
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();
});
Copy link
Copy Markdown

ghost commented Jan 19, 2021

But it didn't work for me. It downloaded by the content of the file is not possible to open.
my back code:

var memory = new MemoryStream();
using (var stream = new FileStream(completeAddress, FileMode.Open))
{
stream.CopyTo(memory);
}
memory.Position = 0;
return new MediaOperationFileStreamViewModel()
{
MediaFileStream = new MediaFileStreamDto()
{
FileId = mediaInfo.Id,
FileName = mediaInfo.Name,
ContentType = Service.Helper.MimeType.GetContentType(completeAddress),
FileStream = memory
}
};
The result will return to controller. Below is my React code :

axios.create({
baseURL: 'https://localhost:44337/api',
timeout: 300000,
maxContentLength: 1073741824,
}).post('/MediaOperation/DownloadFileStream', {
"MediaFileId": item,
responseType: 'blob'
}).then(fileResult => {
const url = window.URL.createObjectURL(new Blob([fileResult.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', currentFileInfo.name);
document.body.appendChild(link);
link.click();
});

@irnadi
Copy link
Copy Markdown

irnadi commented Mar 8, 2021

thank you so much..

@gryphon2411
Copy link
Copy Markdown

This solution requires the entire downloaded file to fit into the browser's memory. Beyond a certain file size, it will either result in out of memory error, or just crash the browser. Terrible idea.

That is correct, what is the solution in this case?

@juandelcano
Copy link
Copy Markdown

juandelcano commented May 19, 2021

pls help me, I already followed all of the tutorial,
the file has been downloaded but it cant be opened caused by corrupted or wrong extension,
what should I do to handle this case?

@radicalloop
Copy link
Copy Markdown

radicalloop commented Jun 22, 2021

Thanks a lot! To set type of file and filename from "content-disposition" -header you can use this:

const blob = new Blob([response.data], {type: response.data.type});
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
const contentDisposition = response.headers['content-disposition'];
let fileName = 'unknown';
if (contentDisposition) {
    const fileNameMatch = contentDisposition.match(/filename="(.+)"/);
    if (fileNameMatch.length === 2)
        fileName = fileNameMatch[1];
}
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
link.remove();
window.URL.revokeObjectURL(url);

getting filename from content-disposition header worked like a charm.. good cleanup at the end as well.

Thanks @LimmaPaulus for https://gist.github.com/javilobo8/097c30a233786be52070986d8cdb1743#gistcomment-2677506

@SwapnilSoni1999
Copy link
Copy Markdown

700th star done :3

@sergiop
Copy link
Copy Markdown

sergiop commented Sep 22, 2021

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');
});

@Hosse-Fernando
Copy link
Copy Markdown

Adding

headers: { 'Accept': 'application/vnd.ms-excel' } Is helpful in download .xlsx files.

been struggling for a while to work with excel file, adding this to my headers solved the problem. thanks a lot!!

@krasni
Copy link
Copy Markdown

krasni commented Oct 17, 2021

Thank you very much. I was struggling for 3 days.

@supunUOM
Copy link
Copy Markdown

Thank you very much. If i not met this solution still searching thank you very much

@ggeser
Copy link
Copy Markdown

ggeser commented Oct 20, 2021

Очень здорово! Спасибо большое!

@rbalink
Copy link
Copy Markdown

rbalink commented Nov 24, 2021

Thanks a lot !

@ZaffranLe
Copy link
Copy Markdown

Many thanks, you saved my day

@lusuee
Copy link
Copy Markdown

lusuee commented Jan 4, 2022

Thanks

@andela-mallan
Copy link
Copy Markdown

Bless you!!!

@ilKhr
Copy link
Copy Markdown

ilKhr commented Jan 30, 2022

Thank you!

@cambur
Copy link
Copy Markdown

cambur commented Mar 30, 2022

This is the fix I've been looking for everywhere

@akshatz
Copy link
Copy Markdown

akshatz commented Jun 10, 2022

Thanks for the solution.

@taofiq-tradelia
Copy link
Copy Markdown

Thanks for the solution 🥲

@AndresCG2019
Copy link
Copy Markdown

AndresCG2019 commented Aug 31, 2022

in a c# rest api what should my endpoint return for axios to take it as a valid "Blob"?

@HighTide2020
Copy link
Copy Markdown

Thanks for the easy snippet & example 🤖

@sdroger
Copy link
Copy Markdown

sdroger commented Jan 10, 2023

Thank you, saved my day!!! S2
it worked perfectly with vue.js

@Neptunium1129
Copy link
Copy Markdown

how to progress download?

@Luiyit
Copy link
Copy Markdown

Luiyit commented Jan 18, 2023

how to progress download?
Maybe the Axios option onDownloadProgress or this package axios-progress-bar can help you

@MustaqueemPathan
Copy link
Copy Markdown

Thank you bro

@myungwoo-Y
Copy link
Copy Markdown

Thank you for great solution!

@Amberevol
Copy link
Copy Markdown

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.

@nurhamsah1998
Copy link
Copy Markdown

thanks

@rr-cory-hartford
Copy link
Copy Markdown

This is great. Thanks

@sabulski
Copy link
Copy Markdown

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!!!

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