我确定没有直接方法可以从文件协议中下载文件,例如file://abc.cmp.com/folder/xyz.txt,所以我尝试使用httpClient获取文件,转换为blob然后下载。 但这也行不通,并出现如下错误:
zone.js:3243 Access to XMLHttpRequest at 'file://abc.cmp.com/folder/xyz.txt' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
示例代码:
sample.html
<td><a [routerLink] = [] (click)="download('file://abc.cmp.com/folder/xyz.txt')">file://abc.cmp.com/folder/xyz.txt')</a></td>
sample.component.ts:
download(url){
let a = document.createElement("a");
document.body.appendChild(a);
let data = this.sampleService.getFileContent(url);
let file = new Blob(data, {type:'text/plain'});
let fileURL = window.URL.createObjectURL(file);
a.href = fileURL;
a.download = 'log';
a.click();
}
sample.service.ts:
getFileContent(url) {
return this.httpClient.get(url)
.subscribe(data => console.log(data));
}
如果有办法解决这个问题,那就太好了。