angular - 上传功能前执行 Image.onload
问题描述
我正在使用角度,并且我有一个执行图像输入的函数。
通过插入的图像,我删除了它们的名称,大小等信息......我的问题是上传图像时(我需要知道它的高度和宽度),上传功能比我从中获取信息的功能先执行那个图像。
作为一个问题,我得到一个未定义的宽度和高度。
上传功能先于 image.onload :(
有谁知道为什么?
组件.ts
detectFiles(event) {
var files = event.target.files;
if (files.length < 8) {
for (let index = 0; index < files.length; index++) {
const item: any = {
filename: event.target.files[index].name.split('.')[0],
};
this.filename = item.filename;
this.items.push(item);
const reader = new FileReader();
reader.onload = (e: any) => {
item.url = e.target.result;
const image = new Image();
image.src = e.target.result;
image.onload = function () {
item.sizeH = image.width;
};
}
formData.append('file', files[index]);
reader.readAsDataURL(files[index]);
}
}
}
解决方案
发生这种情况是因为 onload 是异步的,并且在onload()
仍在运行时,脚本会继续执行并到达upload
.
您可以通过将上传代码移动到它自己的函数中来重构代码,然后从内部调用它,onload()
如下所示:
detectFiles(event) {
...
if (files.length < 8) {
...
reader.onload = (e: any) => {
...
image.onload = function() {
...
uploadFile(formData, stamp, encrPath, sizeH, sizeV); // < Call the upload here
};
};
...
}
}
uploadFile(formData, stamp, encrPath, sizeH, sizeV) {
this.Global.refreshToken().subscribe(function(result) {
self.uploadService
.postImage(formData, stamp, encrPath, sizeH, sizeV)
...
});
}
推荐阅读
- python - tkinter 中一行代码中的多个按钮
- php - 从外部站点向 Laravel 发送 POST 请求
- javascript - 使用 mapDispatchToProps 更改为新的状态值
- javascript - Vue.js Axios 调用当前 URL 我不在我正在调用的那个
- c - 如何通过静态库(macOS)在主进程和动态库之间共享全局变量?
- python - 如何使用 Python C API 在编译的 C 模块中实现 Python 数组
- machine-learning - 是否可以在 python 中在数据集的不同列上训练 2 个 SVM,然后使用两个 SVM 进行最终预测
- asp.net - Cookie 未保存在不同的浏览器中
- javascript - 用ajax显示json_encode的字段
- javascript - Node js - React:获取API请求不返回任何数据