2

Download files with AJAX (axios)

 1 year ago
source link: https://gist.github.com/javilobo8/097c30a233786be52070986d8cdb1743
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Download files with AJAX (axios) · GitHub

Instantly share code, notes, and snippets.

Download files with AJAX (axios)

Thank you man!!!

Thank you buddy! That dark sorcery of yours saved me some hours of sleep heart

Man you are GREAT.

3 Days trying to find a solution, i was close, then i found this solution and the only element i needed was responseType in the request

Thank you so much!

save my job !

Finally! Thank you so much!

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

Thanks for this solution! :D

Thank you so much!

Thanks a lot man 💪🏼

Thanks!!!!

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

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

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

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

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

thank you so much..

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 commented on May 19, 2021

edited

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 commented on Jun 22, 2021

edited

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

700th star done :3

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

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

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

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

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

Thanks a lot !

Many thanks, you saved my day

lusuee commented on Jan 4

Thanks

Bless you!!!

ilKhr commented on Jan 30

Thank you!

cambur commented on Mar 30

This is the fix I've been looking for everywhere


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK