打字稿中'EventTarget'类型错误的属性'files'不存在

问题描述 投票:40回答:6

我正在尝试从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应用程序。

angular typescript ionic2 exif-js
6个回答
44
投票

e.target属性类型取决于您要在getElementById(...)上返回的元素。 filesinput元素的属性: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]; 
    //...
}

54
投票

您可以将其强制转换为HTMLInputElement

document.getElementById("customimage").onchange= function(e: Event) {
    let file = (<HTMLInputElement>e.target).files[0];
    //rest of your code...
}

18
投票

这是更多行,但我认为这是最清晰的。

const onChange = (event: Event) => {
  const target= event.target as HTMLInputElement;
  const file: File = (target.files as FileList)[0];
  /** do something with the file **/
};

8
投票

最简单的解决方案是将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类型。


0
投票

我发现:

<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上对我有用。


0
投票
// 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"));
              });
          }
© www.soinside.com 2019 - 2024. All rights reserved.