Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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();
});
@benalif
Copy link

benalif commented Nov 16, 2020

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.

yes you're right

@pedrofernandes98
Copy link

pedrofernandes98 commented Nov 18, 2020

Thanks for this solution! :D

@johnnyyu0930
Copy link

johnnyyu0930 commented Nov 18, 2020

Thank you so much!

image

@th91vi
Copy link

th91vi commented Nov 23, 2020

Thanks a lot man 💪🏼

@itsalb3rt
Copy link

itsalb3rt commented Nov 23, 2020

Thanks!!!!

@gunkiddedy
Copy link

gunkiddedy commented Nov 30, 2020

thankyou so much, dude... you saved my day :-)....

@shashank5743
Copy link

shashank5743 commented Dec 2, 2020

How to make await until the link is clicked.
I have the code in async downloadFiles and calling inside .then( this.downloadFiles
But it doesn't wait to link to be clicked

@ImAbhishekTomar
Copy link

ImAbhishekTomar commented Jan 12, 2021

Can someone please help, This code is not working for me and not showing any error also?

const download = async (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
  
    const ImageResult = `
    <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 900'><rect fill='#ff7700' width='1600' height='900'/><polygon fill='#cc0000' points='957 450 539 900 1396 900'/><polygon fill='#aa0000' points='957 450 872.9 900 1396 900'/><polygon fill='#d6002b' points='-60 900 398 662 816 900'/><polygon fill='#b10022' points='337 900 398 662 816 900'/><polygon fill='#d9004b' points='1203 546 1552 900 876 900'/><polygon fill='#b2003d' points='1203 546 1552 900 1162 900'/><polygon fill='#d3006c' points='641 695 886 900 367 900'/><polygon fill='#ac0057' points='587 900 641 695 886 900'/><polygon fill='#c4008c' points='1710 900 1401 632 1096 900'/><polygon fill='#9e0071' points='1710 900 1401 632 1365 900'/><polygon fill='#aa00aa' points='1210 900 971 687 725 900'/><polygon fill='#880088' points='943 900 1210 900 971 687'/></svg>
    `;

    if (ImageResult) {
      try {
        const element = document.createElement("a");
        const blob = new Blob([ImageResult], { type: "image/svg+xml" });
        element.href = window.URL.createObjectURL(blob);
        element.download = "myFile.svg";
        document.body.appendChild(element);
        element.click();
        element.remove();
        
      } catch (e) {
        console.log(e);
      }
    }
  };

@houssamboudiar
Copy link

houssamboudiar commented Jan 14, 2021

Duuudeeee that bbangss <3 love you !! you saved my night !

Copy link

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

irnadi commented Mar 8, 2021

thank you so much..

@Eido95
Copy link

Eido95 commented Mar 14, 2021

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

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

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

SwapnilSoni1999 commented Aug 8, 2021

700th star done :3

@sergiop
Copy link

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

Hosse-Fernando commented Oct 12, 2021

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

krasni commented Oct 17, 2021

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

@supunUOM
Copy link

supunUOM commented Oct 17, 2021

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

@ggeser
Copy link

ggeser commented Oct 20, 2021

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

@rbalink
Copy link

rbalink commented Nov 24, 2021

Thanks a lot !

@ZaffranLe
Copy link

ZaffranLe commented Dec 7, 2021

Many thanks, you saved my day

@lusuee
Copy link

lusuee commented Jan 4, 2022

Thanks

@andela-mallan
Copy link

andela-mallan commented Jan 25, 2022

Bless you!!!

@ilKhr
Copy link

ilKhr commented Jan 30, 2022

Thank you!

@cambur
Copy link

cambur commented Mar 30, 2022

This is the fix I've been looking for everywhere

@akshatz
Copy link

akshatz commented Jun 10, 2022

Thanks for the solution.

@taofiq-tradelia
Copy link

taofiq-tradelia commented Aug 14, 2022

Thanks for the solution 🥲

@AndresCG2019
Copy link

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

HighTide2020 commented Sep 7, 2022

Thanks for the easy snippet & example 🤖

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