FileReader() 在 Angular 中返回 undefined 和 fakepath

FileReader() returning undefined and fakepath in Angular

提问人:Scott-MEARN-Developer 提问时间:7/26/2022 更新时间:7/26/2022 访问量:663

问:

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

当我在香草 JS 中执行此操作时,它运行良好。但是现在我在 Angular 中尝试它,并收到以下错误:

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

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

以下是我的代码:

主页.组件.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>

home-page.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);
  }
}

正如我所提到的,我怀疑问题可能出在假路径文件名上,但我不能确定。我是 Angular 的新手,所以任何帮助将不胜感激!谢谢。

JavaScript Angular 文件上传 FileReader

评论


答:

1赞 cvb 7/26/2022 #1

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

因此,该属性(值)没有称为“files”的字段或属性,即数组,因此您会看到错误。

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

评论

0赞 Scott-MEARN-Developer 7/26/2022
这很尴尬。当我发布这个时,我意识到了我的简单错误。谢谢你,我花了一整天的时间才意识到我做错了什么。