小编典典

FileReader() 在 Angular 中返回 undefined 和 fakepath

javascript

我正在尝试创建一个表单,让用户上传一个 csv 文件,然后我将使用 JS 对其进行操作并返回一些对象数组。问题是上传部分。

当我在 vanilla JS 中执行此操作时,它可以完美运行。但现在我在 Angular 中尝试它,我收到以下错误:

错误类型错误:无法读取未定义的属性(读取“0”)

当我 console.log() 上传文件的路径名时,我得到 C:\fakepath\fileName.csv。使用 vanilla JS 时不会发生这种情况,所以我怀疑这个问题可能与此有关。

下面是我的代码:

主页.component.html:

<div class="container">
  <form #myForm id="myForm">
    <div class="row">
      <div class="col-10">
        <label for="csvFile">Select CSV File</label>
        <input class="form-control mb-3" type="file" accept=".csv" #csvFile />
      </div>
      <div class="col-2">
        <!-- <button (click)="myClickFunction($event)" class= "btn btn-secondary mt-4" type="submit" value="Submit">Upload</button> -->
        <input (click)="myClickFunction($event)" class="btn btn-secondary mt-4" type="submit" value="Upload" />
      </div>
    </div>
  </form>
</div>

主页.comomponent.ts:

import {Component, VERSION, ViewChild, ElementRef, OnInit} from "@angular/core";
import { FormsModule, ReactiveFormsModule} from '@angular/forms';
import {FormBuilder} from '@angular/forms';
import { NgModule} from '@angular/core';

@Component({
  selector: 'app-home-page',
  templateUrl: './home-page.component.html',
  styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit {

  constructor() {}

  ngOnInit(): void {}

  @ViewChild('csvFile') csvFile!: ElementRef;
  myClickFunction(event: any) {
    event.preventDefault()
    event.stopPropagation()
    console.log(this.csvFile.nativeElement.value);

    const input =this.csvFile.nativeElement.value.files[0];
    const reader = new FileReader();

    console.log("Form submitted " + input);
  }
}

正如我所提到的,我怀疑问题可能出在 fakepath 文件名上,但我不能确定。我对 Angular 很陌生,所以任何帮助都将不胜感激!谢谢你。


阅读 94

收藏
2022-07-26

共1个答案

小编典典

元素的 .value 属性是一个字符串,其中包含所选文件的路径/位置(出于安全原因,这表示 fakepath)。

因此,该属性(值)没有称为“文件”的字段或属性,它是一个数组,因此您看到的错误。

您可以访问与您的 csvFile 输入关联的文件对象this.csvFile.nativeElement.files[0]

2022-07-26