问题描述
有很多adhoc库支持angular2的上传/下载进度,我不知道如何使用native angular2 http api在上传/下载时显示进度。
Tho there are many adhoc libraries supporting upload/download progress in angular2, I do not know how to do use native angular2 http api to show progress while doing upload/download.
我想使用原生http api的原因是因为我想在本机周围使用
The reason why I want to use native http api is because I want to utilise
- http拦截器(http API包装器)验证,缓存和扩展的http api丰富了发送的实际http请求,例如&
- 除了angular之外,http api比任何adhoc API
- http interceptors(http API wrappers) around native http api that validate, cache & enrich the actual http request being sent such as this & this
- Besides angular's http api is much more robust than any adhoc APIs
来自 @ angular / common / http
。
As of Angular 4.3.x and beyond versions, it can be achieved using the new HttpClient from @angular/common/http
.
阅读部分。
简单上传示例(从上述部分复制):
Simple upload example (copied from the section mentioned above):
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!');
}
});
下载时,它可能几乎相同:
And for downloading, it might be something like pretty much the same:
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必须设置
,否则,无法测量请求。
Remember in case that you're monitoring a download, the Content-Length
has to be set, otherwise, there's no way to the request to be measured.
这篇关于如何使用angular2 http API跟踪上传/下载进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!