Angular 文件下载

    技术2023-06-04  83

    1、需求 在项目开发中,前端使用的是Angular框架,在文件下载的时候遇到问题,文档类型通过超链接可以直接下载,但是图片和pdf文档使用超链接不能下载,只能浏览。

    2、解决办法: ① 创建文件服务 fileService.ts 使用ng generate service file 创建文件,内容如下:

    import { Observable } from 'rxjs'; import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class FileService { constructor(private httpClient: HttpClient) { } download(url: string): Observable<Blob> { return this.httpClient.get(url, {responseType: 'blob'}) } }

    ② 在组件的TypeScript文件中加入fileDownload()方法

    fileDownload(url: string, fileName: string): void { this.fileService .download(url) .subscribe(blob => { const a = document.createElement('a') const objectUrl = URL.createObjectURL(blob) a.href = objectUrl a.download = fileName; a.click(); URL.revokeObjectURL(objectUrl); }) }

    ③ 在组件的HTML模板中使用超链接进行文件下载

    <a (click)="fileDownload('文件下载URL', '文件名')"></a>
    Processed: 0.024, SQL: 9