我正在尝试从ionic 2应用程序访问输入文件的值,但仍然面临'EventTarget'类型不存在属性文件的问题。因为它可以在js中正常工作,但不能在打字稿中工作。代码如下:
document.getElementById("customimage").onchange= function(e?) {
var files: any = e.target.files[0];
EXIF.getData(e.target.files[0], function() {
alert(EXIF.getTag(this,"GPSLatitude"));
});
}
[请帮助我解决此问题,因为它没有构建ionic 2应用程序。
e.target
属性类型取决于您要在getElementById(...)
上返回的元素。 files
是input
元素的属性:https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement
在这种情况下,TypeScript编译器不知道您正在返回input
元素,并且我们没有为此特定的Event
类。因此,您可以创建类似以下代码的代码:
interface HTMLInputEvent extends Event {
target: HTMLInputElement & EventTarget;
}
document.getElementById("customimage").onchange = function(e?: HTMLInputEvent) {
let files: any = e.target.files[0];
//...
}
您可以将其强制转换为HTMLInputElement:
document.getElementById("customimage").onchange= function(e: Event) {
let file = (<HTMLInputElement>e.target).files[0];
//rest of your code...
}
这是更多行,但我认为这是最清晰的。
const onChange = (event: Event) => {
const target= event.target as HTMLInputElement;
const file: File = (target.files as FileList)[0];
/** do something with the file **/
};
最简单的解决方案是将e
声明为any
例如
document.getElementById('customimage').onchange = (e: any) => {
let files = e.target.files[0];
...
};
但是您会丢失类型信息。一种更安全的方法可能是基于FileEvent
声明自己的https://developer.mozilla.org/en-US/docs/Web/API/FileReader/onload类型。
我发现:
<input type="file" accept="image/*"
(change)="upload($event)">
和
<ion-input type="file" accept="image/*"
(change)="upload($event)"><ion-input> or (ionChange)
不会以相同的方式处理事件。因此,event.target
由不同的参数组成。
因此,我没有使用ion-input
标签,但使用了带有<input>
触发器的普通角度(change)="upload($event)"
标签。
它在Ionic 4上对我有用。
// use - ChangeEvent<HTMLInputElement>
document.getElementById("customimage").onchange= function(e?: ChangeEvent<HTMLInputElement>) {
var files: any = e.target.files[0];
EXIF.getData(e.target.files[0], function() {
alert(EXIF.getTag(this,"GPSLatitude"));
});
}