Angular 在上传功能之前执行Image.onload
我正在使用angular,我有一个函数来进行图像输入 通过插入的图像,我删除了它们的信息,如名称、大小。。。 我的问题是,当上传图像时(我需要知道它的高度和宽度),上传功能比从该图像获取信息的功能先执行 作为一个问题,我得到了一个未定义的宽度和高度 首先执行上载功能,然后执行image.onload:( 有人知道为什么吗 组件。tsAngular 在上传功能之前执行Image.onload,angular,typescript,Angular,Typescript,我正在使用angular,我有一个函数来进行图像输入 通过插入的图像,我删除了它们的信息,如名称、大小。。。 我的问题是,当上传图像时(我需要知道它的高度和宽度),上传功能比从该图像获取信息的功能先执行 作为一个问题,我得到了一个未定义的宽度和高度 首先执行上载功能,然后执行image.onload:( 有人知道为什么吗 组件。ts detectFiles(event) { var files = event.target.files; if (files.le
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]);
}
}
}
检测文件(事件){
var files=event.target.files;
如果(files.length<8){
for(让index=0;index{
item.url=e.target.result;
常量图像=新图像();
image.src=e.target.result;
image.onload=函数(){
item.sizeH=image.width;
};
}
append('file',files[index]);
reader.readAsDataURL(文件[索引]);
}
}
}
之所以发生这种情况,是因为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)
...
});
}
检测文件(事件){
...
如果(files.length<8){
...
reader.onload=(e:any)=>{
...
image.onload=函数(){
...
uploadFile(formData、stamp、encrPath、sizeH、sizeV);//<在此处调用上载
};
};
...
}
}
上传文件(formData、stamp、encrPath、sizeH、sizeV){
this.Global.refreshtToken().subscribe(函数(结果){
自助上传服务
.positmage(formData、stamp、encrPath、sizeH、sizeV)
...
});
}