为什么 HttpEventType.UploadProgress 事件在 Angular 文件上传请求中只执行一次?

Max*_*ark 5 file-upload typescript angular

我正在尝试从 angular 上传文件。我也想显示上传进度。

上传服务.ts

public uploadProductImage(obj: FormData, id: string) {
    return this._http.post(baseUrl + `/product/upload`, obj, {
      headers: {
        product_id: id,
      },
      reportProgress : true,
      observe : 'events'
    });
  }
Run Code Online (Sandbox Code Playgroud)

上传.component.ts

uploadClick() {
    const fd = new FormData();

    // for(const f of this.file_url) {
    //   fd.append('image', f.file, f.file.name);
    // }
    fd.append('image', this.file_url[0].file, this.file_url[0].file.name);
    this.service.uploadProductImage(fd, this.product_id.toString())
      .subscribe(
        event => {
          if (event.type === HttpEventType.UploadProgress) {
            console.log(event.loaded, event.total);
            this.progress = Math.round(event.loaded / event.total * 100);

          } else if (event.type === HttpEventType.Response) {
            console.log(event.body);
            this.file_url = [];
          }

        },
        err => {
          console.log(err);
        }
      );
  }
Run Code Online (Sandbox Code Playgroud)

现在图像上传正在工作。只有进度条不起作用。我HttpEventType.UploadProgress立即收到一个事件,event.loaded并且event.total两者都是平等的。

所以progressbar 直接变成了100但是完成请求需要一些时间。

Hal*_*ron 5

我遇到过同样的问题。对我来说,服务器在本地主机上,因此上传是即时的,进度总是 100%。尝试在 Chrome 中限制请求,您将在上传完成之前看到其他一些进度百分比。


如何在 Chrome 中限制网络的步骤:

  1. 打开开发者工具 (F12)
  2. 单击“网络”选项卡
  3. 选择您要模仿的连接类型(“慢速 3G”即可)

  • 该问题没有解决办法,因为问题中的代码在已部署的 Web 应用程序上运行良好。(对我来说)出现进度条百分比的问题是因为 Web api 和 Angular 项目都在本地主机上运行。 (3认同)

Max*_*ark 2

我正在一个新项目中使用这个。它正在发挥作用。希望它能帮助你

import { HttpRequest, HttpEventType, HttpResponse } from '@angular/common/http';


uploadMethod() {
        const formData: FormData = new FormData();
        formData.append('file', this.selectedFile);

        const req = new HttpRequest('POST', apiEndpoint, formData, {
          reportProgress: true,
        });

        this.http.request(req)
        .subscribe(
          (event) => {
            if (event.type === HttpEventType.UploadProgress) {
              // This is an upload progress event. Compute and show the % done:
              this.percentDone = Math.round(100 * event.loaded / event.total);
              console.log(`File is ${this.percentDone}% uploaded.`);
            } else if (event instanceof HttpResponse) {
              console.log('File is completely uploaded!');
              console.log(event.body);
            }
          },
          err => console.error(err)
        );
}
Run Code Online (Sandbox Code Playgroud)