在Angular中遇到"octet-stream - 文件下载不起作用"的问题通常是由于浏览器的安全策略导致的。以下是解决该问题的一种常见方法:
download.service.ts
的服务文件,其中包含以下代码:import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DownloadService {
constructor(private http: HttpClient) {}
downloadFile(url: string): Observable {
return this.http.get(url, {
responseType: 'blob',
headers: new HttpHeaders().append('Content-Type', 'application/octet-stream')
});
}
}
DownloadService
并使用以下代码来触发文件下载:import { Component } from '@angular/core';
import { DownloadService } from './download.service';
@Component({
selector: 'app-download',
template: `
`
})
export class DownloadComponent {
constructor(private downloadService: DownloadService) {}
downloadFile() {
const fileUrl = 'https://example.com/file.pdf'; // 替换为实际的文件URL
this.downloadService.downloadFile(fileUrl).subscribe(response => {
const blob = new Blob([response], { type: 'application/octet-stream' });
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'file.pdf'; // 替换为实际的文件名
link.click();
window.URL.revokeObjectURL(url);
link.remove();
});
}
}
请注意:
downloadFile
方法中,需要将fileUrl
替换为你要下载的文件的实际URL。application/octet-stream
,你可以根据需要更改为其他类型。window.URL.revokeObjectURL(url)
释放URL对象。通过以上步骤,你应该可以成功地在Angular中实现文件下载。