Angular文件上传进度百分比

kom*_*ron 17 file-upload file multipart angular

在我在Angular 4中开发的应用程序中,用户可以将多部分文件上传到服务器中.文件很大.我需要显示文件上传过程的当前进度及其对用户的百分比,我该怎么办?

提前致谢!

Saj*_*ran 30

由于您使用的是Angular4,因此可以Listening to progress使用来自新HttpClient的事件来实现@angular/common/http.

从文档中添加代码,

const req = new HttpRequest('POST', '/upload/file', file, {
  reportProgress: true,
});
Run Code Online (Sandbox Code Playgroud)

然后,

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!');
  }
});
Run Code Online (Sandbox Code Playgroud)

编辑 因为OP希望将它与angular2一起使用,所以应该使用本机JavaScript XHR包装为Observable,如本文所述answer


Ian*_*Ian 16

这适用于 Angular 9 和 10(注意observe: 'events'

const headers = new HttpHeaders({
        'Content-Type': 'application/json',
        Accept: 'application/json',
        Authorization: token
      }))
const formData = new FormData();
formData.append('file_param_name', file, file.name);

this.httpClient.post(url, formData, {
    headers,
    reportProgress: true,
    observe: 'events'
}).subscribe(resp => {
    if (resp.type === HttpEventType.Response) {
        console.log('Upload complete');
    }
    if (resp.type === HttpEventType.UploadProgress) {
        const percentDone = Math.round(100 * resp.loaded / resp.total);
        console.log('Progress ' + percentDone + '%');
    } 
});
Run Code Online (Sandbox Code Playgroud)


Sha*_*tal 9

uploadDocument(file) {

    return this.httpClient.post(environment.uploadDocument, file, { reportProgress: true, observe: 'events' })
}
Run Code Online (Sandbox Code Playgroud)

  • 请考虑添加评论和解释。这将帮助您的读者理解您的代码。[如何回答](https://stackoverflow.com/help/how-to-answer) (5认同)

小智 0

使用 Angular-Loading-Bar 库,如果您不想使用 Angular-Loading-Bar 库,可以使用进度回调 eq-xhrrequest.upload.onprogress。