Chi*_*ari 32 typescript ionic2 exif-js angular
我试图从我的离子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"));
});
}
Run Code Online (Sandbox Code Playgroud)
请帮我解决这个问题,因为它没有构建我的离子2应用程序.
sor*_*deh 45
您可以将其强制转换为HTMLInputElement:
document.getElementById("customimage").onchange= function(e: Event) {
let file = (<HTMLInputElement>e.target).files[0];
//rest of your code...
}
Run Code Online (Sandbox Code Playgroud)
Diu*_*lei 35
该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];
//...
}
Run Code Online (Sandbox Code Playgroud)
这是更多行,但是我认为这是最清楚的。
const onChange = (event: Event) => {
const target= event.target as HTMLInputElement;
const file: File = (target.files as FileList)[0];
/** do something with the file **/
};
Run Code Online (Sandbox Code Playgroud)
最简单的解决方案是声明e为any
例如
document.getElementById('customimage').onchange = (e: any) => {
let files = e.target.files[0];
...
};
Run Code Online (Sandbox Code Playgroud)
但是你丢失了类型信息.更安全的方法可能是FileEvent根据https://developer.mozilla.org/en-US/docs/Web/API/FileReader/onload声明自己的类型.
const onChange => (event: Event): void {
const input = event.target as HTMLInputElement;
if (!input.files?.length) {
return;
}
const file = input.files[0];
console.log(file);
}
Run Code Online (Sandbox Code Playgroud)
小智 5
// 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"));
});
}
Run Code Online (Sandbox Code Playgroud)
小智 5
const handleFileInput = (event: ChangeEvent) => {
const target = event.target as HTMLInputElement;
const file: File = (target.files as FileList)[0];
/** do something with the file **/
};
Run Code Online (Sandbox Code Playgroud)
我会Event改为ChangeEvent,但是德文克拉克的其余答案很棒:)
| 归档时间: |
|
| 查看次数: |
23424 次 |
| 最近记录: |