angluar中文件下载常用的处理方法
接口是Get情况
const url = "https://www.jianshu.com/writer#/notebooks/38692933/notes/50835681"
1.采用window的下载机制
window.location.href = url;
好处:简单易懂
坏处:接口如果有问题,画面就崩溃
window.open().location.href = url;
好处:接口有问题,不影响当前画面
坏处:效果不好,会打卡新窗口
2.采用iframe
html渲染一个隐藏的iframe;
<iframe src="" #video style="display: none" frameborder="0"></iframe>
ts获取dom,赋值url即可
@ViewChild('video') IframeView: ElementRef;
this.IframeView.nativeElement.src = url;
3.接口是POST情况
引入file-saver类库
1.在http请求中加入参数, reportProgress: true, responseType: 'blob',
request(url, params?: any){
const req = new HttpRequest(
'POST',
this.SERVER_URL+url,
params,
{
headers: this.parseHeaders(),
reportProgress: true,
responseType: 'blob',
},
);
return this.http
.request(req);
}
import { saveAs } from 'file-saver';
//此处写自己的业务url,参数
this.http.request('api/v1/Export',obj).subscribe(
(event: any) => {
if (event.type === HttpEventType.ResponseHeader) {
let headerName = event.headers.get('Content-Disposition')
this.fileName = decodeURIComponent(headerName).substring(21)? decodeURIComponent(headerName).substring(21):this.fileName;
} else if (event.type === HttpEventType.DownloadProgress) {
} else if (event instanceof HttpResponse) {
saveAs(event.body,this.fileName);//文件流和文件名
// resolve(true);
}
},
err => {
reject(err);
},
);
.
网友评论