Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
701 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...