【问题标题】:Type 'File | null' is not assignable to type 'File'. in angular 11键入“文件 | null' 不可分配给类型“文件”。在角度 11
【发布时间】:2022-03-05 00:49:15
【问题描述】:

您好,我是 Angular 的新手,目前我正在使用 Angular 11 项目,我必须上传一个 CSV 文件并在客户端提取文件的记录并通过 ASP.NET Web API 将它们保存在数据库中。

这里我按照教程,尝试获取角度侧的CSV文件数据并将它们显示在同一页面中。

然后我得到了这个错误,

键入'文件| null' 不可分配给类型“文件”。 类型 'null' 不可分配给类型 'File'.ts(2322)

我尝试了很多东西,但仍然无法解决这个问题。你能帮帮我吗?

这是我的 .ts 文件,

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-file-upload',
  templateUrl: './file-upload.component.html',
  styles: [
  ]
})
export class FileUploadComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

  lines: any = [];
  linesR: any = [];

  changeListener(files: FileList) {
    console.log(files);
    if (files && files.length > 0) {
      let file: File = files.item(0);
      console.log(file.name);
      console.log(file.size);
      console.log(file.type);

      let reader: FileReader = new FileReader();
      reader.readAsText(file);
      reader.onload = (e) => {
        let csv: any = reader.result;
        let allTextLines = [];
        allTextLines = csv.split(/\r|\n|\r/);

        let headers = allTextLines[0].split(';');
        let data = headers;
        let tarr = [];
        for (let j = 0; j < headers.length; j++) {
          tarr.push(data[j]);
        }
        this.lines.push(tarr);
        let tarrR = [];
        let arrl = allTextLines.length;
        let rows = [];
        for (let i = 1; i < arrl; i++) {
          rows.push(allTextLines[i].split(';'));
        }
        for (let j = 0; j < arrl; j++) {
          tarrR.push(rows[j]);
        }
        this.linesR.push(tarrR);
      }
    }
  }
}

这是我的 .html 文件

    <div class="container">
    <h1 style="text-align: center"> File Upload </h1>
    <br><br>

    <input class="form-control" type="file" class="upload" (change)="changeListener($event.target.files)">

    <table class="table table-bordered table-dark">
        <thead>
            <tr>
                <th *ngFor="let item of lines[0]; let i = index">
                    {{item}}
                </th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let item of linesR[0]; let i = index">
                <td *ngFor="let itemm of lines[0]; let j = index">
                    {{item[j]}}
                </td>
            </tr>
        </tbody>
    </table>
</div>

This is the error I got

谢谢!

【问题讨论】:

  • 改变你的方法就像下面的 changeListener(files: File[]).

标签: angular typescript angular11


【解决方案1】:

尝试使用:

fileupload.component.ts

import { Component, OnInit, VERSION } from "@angular/core";
    
@Component({
  selector: 'app-file-upload',
  templateUrl: './file-upload.component.html',
  styles: []
})
export class FileUploadComponent implements OnInit {
      name = "Angular " + VERSION.major;
    
      lines: any = [];
      linesR: any = [];
    
      ngOnInit() {}
    
      changeListener(files) {
        let fileList = (<HTMLInputElement>files.target).files;
        if (fileList && fileList.length > 0) {
          let file: File = fileList[0];
          console.log(file.name);
          console.log(file.size);
          console.log(file.type);
    
          let reader: FileReader = new FileReader();
          reader.readAsText(file);
          reader.onload = e => {
            let csv: any = reader.result;
            let allTextLines = [];
            allTextLines = csv.split(/\r|\n|\r/);
    
            let headers = allTextLines[0].split(";");
            let data = headers;
            let tarr = [];
            for (let j = 0; j < headers.length; j++) {
              tarr.push(data[j]);
            }
            this.lines.push(tarr);
            let tarrR = [];
            let arrl = allTextLines.length;
            let rows = [];
            for (let i = 1; i < arrl; i++) {
              rows.push(allTextLines[i].split(";"));
            }
            for (let j = 0; j < arrl; j++) {
              tarrR.push(rows[j]);
            }
            this.linesR.push(tarrR);
          };
        }
      }
    }

fileupload.component.html

<div class="container">
  <h1 style="text-align: center">File Upload</h1>
  <br /><br />

  <input
    class="form-control"
    type="file"
    class="upload"
    (change)="changeListener($event)"
  />

  <table class="table table-bordered table-dark">
    <thead>
      <tr>
        <th *ngFor="let item of lines[0]; let i = index">
          {{item}}
        </th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let item of linesR[0]; let i = index">
        <td *ngFor="let itemm of lines[0]; let j = index">
          {{item[j]}}
        </td>
      </tr>
    </tbody>
  </table>
</div>

【讨论】:

  • 您好,Msk,非常感谢。我尝试了这样的答案,changeListener(files: File[]) { // const file: File | undefined = files?.item(0); console.log(files); console.log(files[0]); var file: File = files[0]; //if (file &amp;&amp; files.length &gt; 0) { if (files &amp;&amp; files.length &gt; 0) { let file: File = files.item(0); console.log(file.name); console.log(file.size); console.log(file.type);,现在我收到此错误,“文件 []”类型上不存在属性“项目”。 let file: File = files.item(0); 你能帮帮我吗?
  • 可以用files[0]获取文件
  • 我已经更新了答案。从文件数组中获取文件如下 let file: File = files[0];不使用 files.item(0)
  • 嗨,我试过你的答案。现在我在 .html 文件中遇到这样的错误,Object is possibly 'null'. &lt;input class="form-control" type="file" class="upload" (change)="changeListener($event.target.files)"&gt;Property 'files' does not exist on type 'EventTarget'. &lt;input class="form-control" type="file" class="upload" (change)="changeListener($event.target.files)"&gt;
  • 试试这个 stackblitz 例子,stackblitz.com/edit/…
【解决方案2】:

如果您确定您将在文件项中包含值,那么您可以说:

let file: File = files.item(0) as File;

【讨论】:

  • 嗨,谢谢,我试过了,现在它给出了这个错误,error TS2531: Object is possibly 'null'. &lt;input class="form-control" type="file" class="upload" (change)="changeListener($event.target.files)"&gt;error TS2339: Property 'files' does not exist on type 'EventTarget'. &lt;input class="form-control" type="file" class="upload" (change)="changeListener($event.target.files)"&gt;
【解决方案3】:

您正在使用带有打字稿的strict: true。那挺好的!你面临的问题是这件作品:

let file: File = files.item(0);

可以返回未定义,即使您之前检查了长度。这将使类型为File | null ,但您说它应该只是File

最好将其更改为以下内容:

changeListener(files: FileList) {
 const file: File | null = files?.item(0);

 if (file) {
   // here `file` will have type `File` because it has been asserted with the `if`
      console.log(file.size);
      console.log(file.type);

      let reader: FileReader = new FileReader();
      reader.readAsText(file);
      reader.onload = (e) => {
  //...
 

【讨论】:

  • 嗨,波尔,非常感谢。我尝试了这样的答案,changeListener(files: FileList) { const file: File | undefined = files?.item(0); console.log(files); if (file &amp;&amp; files.length &gt; 0) { //if (files &amp;&amp; files.length &gt; 0) { //let file: File = files.item(0); console.log(file.name); console.log(file.size); console.log(file.type);,现在我收到了这个错误。 键入'文件| null' 不可分配给类型 'File |不明确的'。类型 'null' 不能分配给类型 'File | undefined'.ts(2322) 你能帮帮我吗?
  • @kalpana 正确,如果item 不存在,它将返回null 而不是未定义。我已经更新了答案
【解决方案4】:

我对此没意见:

const file = files.item(0);
if (file && file !== null) {
  ...

还有这个:

const file: any = files.item(0);
if (file && file !== null) {
  ...

即使我使用的是files[0] 而不是files.item(0)。而这一切都在strict 模式下进行。

【讨论】:

  • 嗨,谢谢,我试过了,现在报这个错误,Object is possibly 'null'. &lt;input class="form-control" type="file" class="upload" (change)="changeListener($event.target.files)"&gt;Property 'files' does not exist on type 'EventTarget'. &lt;input class="form-control" type="file" class="upload" (change)="changeListener($event.target.files)"&gt;
  • 我已经更新了我的答案。现在我在您的错误中看到另一个问题:Property 'files' does not exist on type 'EventTarget'。您可以而且必须先解决这个问题,然后才能修复 item(0) 问题。也许在参数部分尝试files: Event 而不是files
【解决方案5】:

另一种解决方案是 -

let file: File | any = null;

let file: File | null = null;

【讨论】:

    【解决方案6】:

    如果你想将文件设为 Null,请执行此操作 file= new File([],''); 它会将文件对象重新初始化为空文件对象

    【讨论】:

      猜你喜欢
      • 2021-06-08
      • 2021-11-08
      • 2022-09-30
      • 2021-06-12
      • 2018-10-26
      • 2018-07-01
      • 1970-01-01
      • 2016-08-26
      • 1970-01-01
      相关资源
      最近更新 更多