在我在Angular 4中开发的应用程序中,用户可以将多部分文件上传到服务器。 文件很大。 我需要显示文件上传过程的当前进度及其对用户的百分比,我该怎么做?
提前致谢!
In my application that i am developing in Angular 4, user can upload multipart files into server. Files are large. I need to show the current progress of file upload process with it's percentage to user, how can i do it?
Thanks in advance!
最满意答案
由于您使用的是Angular4,因此可以使用@angular/common/http.的新HttpClient Listening to progress事件@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!'); } });编辑由于OP想与angular2一起使用它,应该使用原生JavaScript XHR作为Observable包装,如此answer
Since you are using Angular4 , it can be achieved using Listening to progress events using the new HttpClient from @angular/common/http.
Adding code from the docs,
const req = new HttpRequest('POST', '/upload/file', file, { reportProgress: true, });and then,
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!'); } });EDIT Since OP wanted to use it with angular2, should use native JavaScript XHR wrapped as an Observable as mentioned in this answer
更多推荐
发布评论