Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download file not working

I am new to Javascript, I want to download a file that comes from a dynamic url after the result of a promise, it is a generated pdf which I am trying to download with the following call but unable to make it work as download doesn't start.

<button (click)='downloadMyFile()'>Download</button>

downloadMyFile(){
  //url 
  .then((result)=>{
   //result is contains a url www.abc.com/file234
    window.location.href = result
})
  .catch((error)=>{
   //myerror
})
}

Here is plunk

like image 420
localhost Avatar asked Apr 20 '18 14:04

localhost


1 Answers

You can force download file like this:

const link = document.createElement('a');
link.href = result;
link.download = 'download';
link.target = '_blank';
link.click();

Simply create anchor tag, set its href and download attributes and trigger click event.

Also note that this is not really about URL ending with extension or not - it is more about the headers that you send with the file response (namely Content-Type and Content-Disposition).

like image 63
Martin Adámek Avatar answered Sep 22 '22 17:09

Martin Adámek