1

My code works in google chrome that provide download and in firefox it always show in new tab or selftab like XML file open in firefox how should I can download it? So provide me some suggestion to download functionality in angular JS or Java script for Firefox! This is my code which I tried

var link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', filename);
Himanshu
  • 12,071
  • 7
  • 46
  • 61
Er Abdul Meman
  • 163
  • 1
  • 9
  • Where does `url` points to in regard to your current page? – Kaiido Feb 06 '18 at 12:37
  • URL points to s3-server to get file – Er Abdul Meman Feb 06 '18 at 13:19
  • Do you know Balaji Damodare? He asked the same question 1hour before you did. https://stackoverflow.com/questions/48641375/html5-download-attribute-not-working-for-mozilla/48642634?noredirect=1#comment84283050_48642634 – Kaiido Feb 06 '18 at 13:23
  • No I don't know but I am working from 2 days to find out solution for this, but I didn't find any solution – Er Abdul Meman Feb 06 '18 at 13:37
  • A possible workaround, depending on your s3 config: `fetch(url).then(r=>r.blob()).then(b=>{let a=document.createElement('a'); a.href=URL.createObjectURL(b);a.download=filename;document.body.appendChild(a);a.click();document.body.removeChild(a);`. – Kaiido Feb 06 '18 at 13:59
  • I know this createOvjectURL but dude i don't have any data or object , i just have URL for download file from s3 server – Er Abdul Meman Feb 06 '18 at 14:01
  • Try the code I gave (replacing `url` with the actual url) and cehck your console for an error. If it tells something like cross-origin request blocked, then you're screwed. – Kaiido Feb 06 '18 at 14:04
  • "fetch(url).then(r=>r.blob()).then(b=>{ let a=document.createElement('a'); } " bro this code is not working in angular Js it give's syntax error first – Er Abdul Meman Feb 06 '18 at 14:26

2 Answers2

5

The anchor tag you are creating also needs to be added to the DOM in Firefox, in order to be recognized for click events.

document.body.appendChild(link);
link.click();
Catalin Iancu
  • 722
  • 5
  • 18
3

The problem is, that you have to encode the url with javascript function encodeURIComponent(URI) and, like Catalin lancu said before me, add the anchor tag to the DOM.

Here is a function I wrote some time back to download files:

function downloadFile(content, filename, type){
  var a = document.createElement('a');
  a.href = type+','+encodeURIComponent(content);
  a.target = '_blank';
  a.download = filename;
  document.body.append(a);
  a.click();
  document.body.removeChild(a);
}

Hope this helps.

lance dörksen
  • 193
  • 1
  • 2
  • 8