Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download a file from asset folder when clicking on a button

I am working on an angular2 project, I have a file in assets folder and I have created a button to download the file while running the app.

I see there are quite a many solutions to the above problem so i got confused. Can you please help.

<button pButton type="button" (click)="f1()" label="Download Sample Defaults 
XML File"></button>

I need code for f1() which can help me download the file to my Download folder when clicking on above button. Help appreciated. Thanks

like image 630
Sunil Bishnoi Avatar asked Jun 18 '18 10:06

Sunil Bishnoi


People also ask

How do you download a file from a URL when a button is clicked in angular?

With the use of the tag download attribute, we can download pdf files, images, word files, etc. The download attribute specifies that the target (the file specified in the href attribute) will be downloaded when a user clicks on the hyperlink.

How do I download a link to a file?

Most files: Click on the download link. Or, right-click on the file and choose Save as. Images: Right-click on the image and choose Save Image As. Videos: Point to the video.


2 Answers

You can either style an anchor element to look like a button and set it's href to assets/file

<a href="assets/file">Download here</a>

Or create an anchor element on the fly, set it's href element and click it.

Something like:

let link = document.createElement('a');
link.setAttribute('type', 'hidden');
link.href = 'assets/file';
link.download = path;
document.body.appendChild(link);
link.click();
link.remove();
like image 83
Carsten Avatar answered Oct 18 '22 19:10

Carsten


You don't need to change the template. Use this way

f1() {
    window.open('path', '_blank');
}

ex:

f1() {
   window.open('/assets/images/blabla.png', '_blank');
}

update

If you need to download file instead of opening a new tab use a link with html5 download attribute ex:

<a download="filename" target="_blank" href="/assets/images/blabla.png">
  Click here to download image
</a>
like image 20
SFernando Avatar answered Oct 18 '22 19:10

SFernando