转换 document.getElementById 以访问 TypeScript 中的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35808809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:19:54  来源:igfitidea点击:

Casting document.getElementById to access files in TypeScript

javascripthtmlangularjsfile-uploadtypescript

提问by Sailoosha

I am very new to angularjs. I wasn't able to find the solution online. I would like to read the text from a file. I was trying to follow this example. FileReader not loading file properly using AngularJS

我对 angularjs 很陌生。我无法在网上找到解决方案。我想从文件中读取文本。我试图遵循这个例子。 FileReader 未使用 AngularJS 正确加载文件

However, since I'm using TypeScript, I receive this error for this line

但是,由于我使用的是 TypeScript,因此我收到此行的错误

document.getElementById('fileInput').files[0];

Error: Property 'files' does not exist on type 'HTMLElement'.

错误:“HTMLElement”类型上不存在属性“files”。

Please suggest me how I can cast to use the files.

请建议我如何投射以使用这些文件。

回答by mutex

Another way I've found around the error in the question is to replace:

我在问题中找到的错误的另一种方法是替换:

document.getElementById('fileInput').files[0];

with

var input: any = document.getElementById('fileInput');
var file = input.files[0];

by defining input as type "any" the Typescript compiler no longer raises the error.

通过将输入定义为“任何”类型,Typescript 编译器不再引发错误。

回答by Ammar Hasan

This should work fine from that example, maybe you're doing something wrong there. However, you may test your code like this, replace fileChanged()by fileChanged(event)and then get the files by event.target.files

从那个例子来看,这应该可以正常工作,也许你在那里做错了什么。但是,您可以像这样测试您的代码,替换fileChanged()fileChanged(event),然后通过以下方式获取文件event.target.files

function fileChanged(event) {
  var target = event.target || event.srcElement;
  console.log(target.files);
  console.log(document.getElementById('fileInput').files);
}
<div>
  <input ng-model="csv"
            onchange="fileChanged(event)"
            type="file" id="fileInput"/>
</div>

回答by Steve

you should cast it to HTMLInputElement. That interface has the .filesfield defined to be FileList

你应该把它投射到HTMLInputElement. 该接口的.files字段定义为FileList

/**
 * Returns a FileList object on a file type input object.
 */
readonly files: FileList | null;

interface FileList {
    readonly length: number;
    item(index: number): File;
    [index: number]: File;
}