【问题标题】:TypeScript : Not being able to iterate line by line over a uploaded file(Angular 9)TypeScript:无法逐行迭代上传的文件(Angular 9)
【发布时间】:2020-09-03 06:24:19
【问题描述】:

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

core.js:6260 ERROR TypeError: this.firstfile.split 不是函数 或者它的返回值是不可迭代的 在 AppComponent.firstfileupload (app.component.ts:23) 在 AppComponent_Template_input_change_2_listener (app.component.html:2) 在 executeListenerWithErrorHandling (core.js:21815) 在 wrapListenerIn_markDirtyAndPreventDefault (core.js:21857) 在 HTMLInputElement。 (平台-browser.js:976) 在 ZoneDelegate.invokeTask (zone-evergreen.js:399) 在 Object.onInvokeTask (core.js:41640) 在 ZoneDelegate.invokeTask (zone-evergreen.js:398) 在 Zone.runTask (zone-evergreen.js:167) 在 ZoneTask.invokeTask [作为调用] (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>

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

【问题讨论】:

  • 这能回答你的问题吗? Angular - Read a file and parse its content
  • 我的问题有点不同。感谢反馈
  • 答案是完全一样的......
  • 我认为这里的答案比那里的答案更清晰,实现更好。但是,如果您仍然想关闭它,您可以。

标签: javascript angular typescript angular9


【解决方案1】:

您可以尝试使用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,这些events 根据各自的操作触发。

+------------+------------------------------------ --------------------------------------------+ |活动名称 |被解雇时… | +------------+------------------------------------ --------------------------------------------+ |加载启动 |当读取开始时。 | |进展 |读取(和解码)blob | |中止 |当读取被中止时。 | | |例如,通过调用 abort() 方法。 | |错误 |读取失败时(请参阅文件读取错误)。 | |加载 |当读取成功完成时。 | |负载端 |请求完成时(成功或失败)。 | +------------+------------------------------------ --------------------------------------------+

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

您可以在此处了解有关异步数据的更多信息:https://stackoverflow.com/a/14220323/6513921

【讨论】:

  • 但是你能向我解释一下你的代码吗?那个readFileContent我没看懂,如果你能解释一下或者参考一些教程让我更好地理解它,那将对我有很大帮助。
  • 我已经添加了一些内联的解释并附上了一些来源。
  • 你能给我一些链接,在那里我可以学习如何显示文件的内容吗?
【解决方案2】:

基于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 帮助器来迭代文件内容。

检查这个:Angular - Read a file and parse its content

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 2011-01-18
    • 2019-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多