因此,有许多临时库支持 Angular2 中的上传/下载进度,我不知道如何使用本机 Angular2 http api 在上传/下载时显示进度。
我想使用原生http api的原因是因为我想利用:
- 围绕本机 http api 的 http 拦截器(http API 包装器),用于验证、缓存和丰富正在发送的实际 http 请求,例如this & this
- Angular 的 http api 比任何 ad hoc API 都要健壮得多
有一篇好文章关于如何使用 Angular 的 http api 进行上传/下载
但文章提到,没有原生方法来支持进展。
有人尝试使用 http api 来显示进度吗?
如果没有,您知道角度存储库中存在此问题吗?
从 Angular 4.3.x 及更高版本开始,可以使用新的实现Http客户端 from @angular/common/http
.
阅读监听进度事件部分。
简单的上传示例(从上面提到的部分复制):
const req = new HttpRequest('POST', '/upload/file', file, {
reportProgress: true,
});
http.request(req).subscribe(event => {
// Via this API, you get access to the raw event stream.
// Look for upload progress events.
if (event.type === HttpEventType.UploadProgress) {
// This is an upload progress event. Compute and show the % done:
const percentDone = Math.round(100 * event.loaded / event.total);
console.log(`File is ${percentDone}% uploaded.`);
} else if (event instanceof HttpResponse) {
console.log('File is completely uploaded!');
}
});
对于下载来说,它可能几乎是一样的:
const req = new HttpRequest('GET', '/download/file', {
reportProgress: true,
});
http.request(req).subscribe(event => {
// Via this API, you get access to the raw event stream.
// Look for download progress events.
if (event.type === HttpEventType.DownloadProgress) {
// This is an download progress event. Compute and show the % done:
const percentDone = Math.round(100 * event.loaded / event.total);
console.log(`File is ${percentDone}% downloaded.`);
} else if (event instanceof HttpResponse) {
console.log('File is completely downloaded!');
}
});
请记住,如果您正在监控下载,Content-Length
必须设置,否则无法测量请求。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)