我想知道为什么下面的代码适用于chrome和edge而不是firefox。
downloadFile(uri, name){
this.http.get(uri, {responseType: 'blob'})
.subscribe(res =>{
var a = document.createElement("a");
a.href = URL.createObjectURL(res);
a.download = name;
a.click();
}, error => {this.errorHandler.addError(this.constructor.name, error);});}
非常感谢您的帮助,谢谢!
答案 0 :(得分:0)
从http mudule中包含ResponseContentType以下载文件。
//service file. Create this method in your service file where you added all services.
import { Headers, Http, RequestOptions, ResponseContentType } from '@angular/http';
download(uri) {
return this.http.get(uri, { responseType: ResponseContentType.Blob })
.map((res) => {
return new Blob([res.blob()], { type: 'application/pdf' }) //change file type here
})
}
然后使用createObjectURL
创建响应的对象//component.ts
this.service.download(uri)
.subscribe(res => {
saveAs(res,"filename.ext");
let fileURL = URL.createObjectURL(res);
window.open(fileURL);
})
这适用于所有浏览器。