单击按钮时从资产文件夹下载文件

Download a file from asset folder when clicking on a button

我正在做一个 angular2 项目,我在 assets 文件夹中有一个文件,我创建了一个按钮来下载该文件,同时 运行 应用程序。

我看到有很多解决上述问题的方法,所以我很困惑。你能帮忙吗

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

我需要 f1() 的代码,它可以帮助我在单击上面的按钮时将文件下载到我的下载文件夹。帮助表示赞赏。谢谢

您可以将锚元素的样式设置为看起来像按钮并将其 href 设置为 assets/file

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

或者动态创建一个锚元素,设置它的 href 元素并单击它。

类似于:

let link = document.createElement('a');
link.setAttribute('type', 'hidden');
link.href = 'assets/file';
link.download = path;
document.body.appendChild(link);
link.click();
link.remove();

您不需要更改模板。这样使用

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

例如:

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

更新

如果您需要下载文件而不是打开新标签页,请使用带有 html5 download 属性的 link 例如:

<a download="filename" target="_blank" href="/assets/images/blabla.png">
  Click here to download image
</a>

你可以试试这个解决方案

ts file code

downloadFile(){
        let link = document.createElement("a");
        link.download = "filename";
        link.href = "assets/images/user-image.png";
        link.click();
}

html file code

<button (click)="downloadFile()">Download</button>

这应该有效,简短而简单,"download" 和“#”-"yoclickme" 使其有效

<a href="{{ this.fileurl }}" download #yoclickme></a> 
    <button (click)="yoclickme.click()"> Download </button>

你可以试试这个。 将文件放在assets中,在href中给出路径。

<a class="iconsBG" title="Excel" href='/assets/Project-2021-05-17T10_41_22.378Z.xlsx' download="Project-2021-05-17T10_41_22.378Z.xlsx"><i class="far fa-file-excel"></i></a>