如何检测表单更改事件何时完成(将文件转换为 base64)

How to Detect When Form Change Event has Finished ( converting file to base64 )

我正在将文件上传到 API,该 POST 请求包含 base64 信息以便 "upload" 文件(API 提供程序不接受二进制文件上传)。它适用于中小型文件(小于 2MB)。

我在 Angular 中通过在选择文件时捕获更改事件来执行此操作:

<input #file type="file" (change)="upload($event)" />

然后,在我的 upload() 方法中,我使用 readAsDataURL() 方法将 $event 数据转换为 base64。最后,有一个按钮可以按下,它使用 base64 数据和凭据向我的 API 发送 POST 请求。

当文件较小且 base64 编码速度很快时效果很好,但当文件较大(大约 4MB 或更大)时,编码需要很长时间,因此用户无法判断是否已完成编码。如果他们按下按钮发送 POST,如果编码没有完成,它将失败。

有没有办法检测编码何时完成或以某种方式监控编码进度?

原来FileReader的构造函数有一个叫做"onprogress"的事件可以报告当前的进度。我需要做的就是将 "onprogress" 属性 附加到我的 FileReader 实例,然后我可以在事件中使用 "lengthComputable" 获得进度(我的示例使用 Angular 2 / 4):

showProgress: number;

let myReader: FileReader = new FileReader();

myReader.onprogress = (e) => {
  if (e.lengthComputable) {
    //Round the progress to a percent whole number 
    this.showProgress = Math.round(100 * e.loaded / e.total);
    return this.showProgress;
  }
}

然后为了将此进度输出绑定到 Bootstrap 进度条,我的 html 如下所示:

<div class="progress">
           <div class="progress-bar" role="progressbar" [ngStyle]="{ 'width': showProgress + '%' }">
               <span class="sr-only">{{ showProgress }}% Complete</span>
           </div>
   </div>