要实现通过Angular路由下载文件,可以使用以下步骤:
file-saver
和@angular/http
模块。可以使用以下命令进行安装:npm install file-saver @angular/http --save
import { Injectable } from '@angular/core';
import { Http, ResponseContentType } from '@angular/http';
import { saveAs } from 'file-saver';
@Injectable()
export class DownloadService {
constructor(private http: Http) {}
downloadFile(url: string, fileName: string) {
this.http.get(url, { responseType: ResponseContentType.Blob })
.subscribe(response => {
const blob = new Blob([response.blob()], { type: response.headers.get('Content-Type') });
saveAs(blob, fileName);
});
}
}
import { Component } from '@angular/core';
import { DownloadService } from './download.service';
@Component({
selector: 'app-file-download',
template: `
`
})
export class FileDownloadComponent {
constructor(private downloadService: DownloadService) {}
download() {
const fileUrl = 'https://example.com/file.pdf';
const fileName = 'example.pdf';
this.downloadService.downloadFile(fileUrl, fileName);
}
}
在上述示例中,downloadFile
方法使用Http
模块来获取文件的Blob
数据,并利用file-saver
模块中的saveAs
方法将文件保存到用户的设备上。
注意:在实际使用中,你需要替换fileUrl
和fileName
为你要下载的文件的实际URL和文件名。
这样,当用户点击"Download File"按钮时,将会触发文件下载。