首页 > 解决方案 > 从图像转换为 Base64 字符串在 Javascript 或 Typescript 中响应非常慢

问题描述

我想在打字稿中将图像文件转换为 base64 字符串,但这个过程非常慢

base64Media = '';
uploadFile(fileItem: FilePreviewModel): Observable<any> {
 const reader = new FileReader();
 reader.onloadend = () => {
  this.base64Media = reader.result;
 }
 reader.readAsDataURL(fileItem.file);
 return this.api.upload({this.base64Media});
}

base64Media 变量转到后端服务,但其值为空。我也试过 Promise 但还是不行

标签: javascripttypescriptrxjs

解决方案


发生了多个异步回调。第一个是uploadevent,第二个是完整数据的“加载”。


      const reader = new FileReader();
      // happens async
      reader.onload = (e: ProgressEvent) => {
        const image = new Image();
        image.src = (e.target as FileReader).result as string;

        image.onload = (event: Event) => {
          const imgBase64Path = (e.target as FileReader).result as string;
          this.base64Media = this.sanitizer.bypassSecurityTrustUrl(imgBase64Path);
          //only when this point is reached the data is there. 
        };

    };
    // this triggers a async call
    reader.readAsDataURL((uploadEvent.target as HTMLInputElement).files[0]);

    // this will be executed instantly after, but won't wait of async execution. 
    // this api call should be inside the "image onload"- part above. 

    return this.api.upload({this.base64Media})

您可以做的是使用“可观察”来传递数据,从而触发回调。

或者将 api 调用放在 onload-Callback 中。

但这取决于您要返回的内容。


推荐阅读