5

Html File

<button mat-button (click) = "FileDownload">Download</button>

Anugular 4 Component Method

FileDownload()
{
  this.filePath = "D:\SamplePDF.pdf";
  document.loation.href = this.filePath;

}

Here, I want to download the local file when button click happens. I am not able to download the file. Please help.

PS: I am not able to access window.open() also as I am using angular 4 application.

Billy
  • 825
  • 6
  • 21
  • 36

5 Answers5

3

Can you try this snippet

function downloadFunc(){
     var anchor=document.createElement('a');
     anchor.setAttribute('href','D:/SamplePDF.pdf');
     anchor.setAttribute('download','');
     document.body.appendChild(anchor);
     anchor.click();
     anchor.parentNode.removeChild(anchor);
  }
Patharraj
  • 41
  • 2
  • 1
    I have used your code but getting the same error in console: Not allowed to load local resource. – Billy Aug 01 '18 at 08:34
  • btw I have tried different approach using https://gist.github.com/liabru/11263260 – Billy Aug 01 '18 at 17:54
  • "Not allowed to load local resource" Local file and Server are different that the time get that issue. Other wise you have try convert local file into blob data and then set anchor element it will might help. – Patharraj Aug 03 '18 at 05:57
1

You can simply do like this.

<a href="your_link" download> file_name </a>

Use a tag instead of button and implement material button style there. And use download attribute to implement the download action.

Derek Wang
  • 10,098
  • 4
  • 18
  • 39
0

Could you try something like this:

/**
 * Method is use to download file.
 * @param data - Array Buffer data
 * @param type - type of the document.
 */
downLoadFile(data: any, type: string) {
    var blob = new Blob([data], { type: type.toString() });
    var url = window.URL.createObjectURL(blob);
    window.open(url);
}
Akj
  • 7,038
  • 3
  • 28
  • 40
0

¿Are you using ngnix or apache? You can force download with ngnix or apache by sending the content as an "attachment" (using "Content-Disposition" header).

This is a sample config to do this with Nginx:

server {
    listen 80;
    server_name my.domain.com;
    location ~ ^.*/(?P<request_basename>[^/]+\.(pdf))$ {
        root /path/to/pdf/
        add_header Content-Disposition 'attachment; filename="$request_basename"';
    }
}
Javier Rojano
  • 814
  • 9
  • 17
-3

try this

javascript:

window.open('file:///c://Documents/folder/file.ext', 'Download');

html:

<a href="file:///C://Documents/folder/file.ext">Download Me</a>
Tim Diekmann
  • 7,755
  • 11
  • 41
  • 69
Kanna
  • 125
  • 1
  • 1
  • 10