javascript - 从图像转换为 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 但还是不行
解决方案
发生了多个异步回调。第一个是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 中。
但这取决于您要返回的内容。
推荐阅读
- git - 寻找一个在关闭文件时自动提交 git 的文本编辑器
- email - BIND DKIM 语法错误
- javascript - 我想在这段代码中显示 Fetched API
- geode - 获取 java.lang.IllegalStateException:无法在定位器中创建区域
- linux - 无法使用 ffmpeg 录制窗口
- angular - 带有静态数据的材料设计数据表布局
- javascript - jQuery自定义手风琴,关闭其他打开的li
- c# - 即使在文本框中没有输入任何内容,C# 我也在尝试进行自动完成显示
- dart - Dart build_runner 只能扫描/读/写 web/ 目录下的文件?
- java - 为什么在 Java 中会发生这种情况?