TypeScript:无法逐行迭代上传的文件(Angular 9)

TypeScript : Not being able to iterate line by line over a uploaded file(Angular 9)

我想在我的 Angular 应用程序中逐行迭代用户上传的文件。我已尝试此 中所述的方法,但出现以下错误:

core.js:6260 ERROR TypeError: this.firstfile.split is not a function or its return value is not iterable at AppComponent.firstfileupload (app.component.ts:23) at AppComponent_Template_input_change_2_listener (app.component.html:2) at executeListenerWithErrorHandling (core.js:21815) at wrapListenerIn_markDirtyAndPreventDefault (core.js:21857) at HTMLInputElement. (platform-browser.js:976) at ZoneDelegate.invokeTask (zone-evergreen.js:399) at Object.onInvokeTask (core.js:41640) at ZoneDelegate.invokeTask (zone-evergreen.js:398) at Zone.runTask (zone-evergreen.js:167) at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:480)

我的代码 app.component.ts

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  firstfile=null;
  second_file = null;
  title = 'first';

  constructor(private http:HttpClient){

  }

  firstfileupload(event){
    console.log("First file")
    console.log(event)
    this.firstfile=event.target.files[0]
    for(const line of this.firstfile.split(/[\r\n]+/)){
      console.log(line)
    }
    console.log("First file File has been changed")
  }
  secondfile(event){
    this.second_file=event.target.files[0];
    // for(const line of this.second_file.split(/[\r\n]+/)){
    //   console.log(line)
    // }
    console.log("Second file uploaded")
  }
  onUpload(){
    console.log("Upload button clicked")
    // const fd = new FormData();
    // fd.append('files',this.firstfile);
    // fd.append('files',this.second_file);
    // this.http.post('http://localhost:5000',fd).subscribe(res =>{
    //   console.log(res)
    // }

    // )
  }
}

app.component.html

<h1>Upload the files</h1>
<input type="file" (change)="firstfileupload($event)">
<input type="file" (change)="secondfile($event)">
<button type="button" (click)="onUpload()">Upload</button>

如何遍历上传的文件?我宁愿不保存文件而只是在那里迭代。 提前致谢。

你的问题,基于 this.firstfile.split is not a function or its return value is not iterable 错误,是你试图迭代一个对象(即文件),而不是它的内容。

firstfileupload(event){
    . . .
    this.firstfile=event.target.files[0]  // <<<----- You recover the file. As OBJECT
    for(const line of this.firstfile.split(/[\r\n]+/)){ // <<<--- You want to iterate the OBJECT like it is an STRING element
      . . .
    }
    . . .
  }

您需要使用 FileReader 助手来迭代文件内容。

检查这个:

您可以尝试使用 FileReader.readAsText() 读取文件的内容。尝试以下

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { Observable, Subject } from 'rxjs';

export class AppComponent {
  ...

  firstfileupload(event) {
    this.firstfile = event.currentTarget.files[0];

    this.readFileContent(event.currentTarget.files[0]).subscribe(
      content => {
        for(const line of content.split(/[\r\n]+/)) {
          if (line !== '') {          // <-- regex pattern might return an empty line at the EOF
            console.log(line);
          }
        }
      }
    );

    console.log("First file File has been changed")
  }

  private readFileContent(file): Observable<any> {
    let result = new Subject<any>();           // <-- Step 1: Create an empty RxJS `Subject`

    const reader = new FileReader();           // <-- Step 2: Create a `FileReader` object
    reader.onload = (e) => {                   // <-- Step 5: Callback function to trigger on the evnet `onload`
      const fileContent = e.target.result;     // <-- Step 6: `event.target.result` contains the file content
      result.next(fileContent);                // <-- Step 7: Push the file contents to the `result` subject
    };
    reader.readAsText(file);                   // <-- Step 3: Read the file using `FileReader`'s method `readAsText`

    return result.asObservable();              // <-- Step 4: Return the `result` subject
  }
}

FileReaderFile API 的一部分。它包含以下 events,它们根据各自的操作触发。

+------------+----------------------------------------------------------------+
| Event name | Fired when…                                                    |
+------------+----------------------------------------------------------------+
| loadstart  | When the read starts.                                          |
| progress   | While reading (and decoding) blob                              |
| abort      | When the read has been aborted.                                |
|            | For instance, by invoking the abort() method.                  |
| error      | When the read has failed (see file read errors).               |
| load       | When the read has successfully completed.                      |
| loadend    | When the request has completed (either in success or failure). |
+------------+----------------------------------------------------------------+

我们正在创建对象并使用 load 事件的回调函数读取文件内容。由于数据处理是异步的,我们使用 RxJS Subject 来异步读取函数 readFileContent 返回的数据。

您可以在此处了解有关异步数据的更多信息: