Troubleshooting in TypeScript: Difficulty iterating line by line through an uploaded file on Angular 9 platform

I need to loop through a user uploaded file line by line within my Angular application. I attempted the method mentioned in this solution but encountered the following issue:

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)

Here's the snippet from 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)
    // }

    // )
  }
}

As well as 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>

Is there a way to iterate over an uploaded file without saving it? Any help would be greatly appreciated.

Answer №1

If you're looking to access the contents of a file, consider utilizing the FileReader.readAsText() method. Below is an example:

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 !== '') {         
            console.log(line);
          }
        }
      }
    );

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

  private readFileContent(file): Observable<any> {
    let result = new Subject<any>();           

    const reader = new FileReader();           
    reader.onload = (e) => {                   
      const fileContent = e.target.result;     
      result.next(fileContent);                
    };
    reader.readAsText(file);                   

    return result.asObservable();              
  }
}

The FileReader belongs to the File API, offering various events based on different actions.

load event. This facilitates the reading of file content asynchronously via the function readFileContent.

For further insights into asynchronous data processing, check out:

Answer №2

The issue you are facing, as indicated by the error message

this.firstfile.split is not a function or its return value is not iterable
, is that you are attempting to loop through an object (in this case, the file itself) rather than its actual contents.

firstfileupload(event){
    . . .
    this.firstfile=event.target.files[0]  // <<<----- Here, you are storing the file as an OBJECT
    for(const line of this.firstfile.split(/[\r\n]+/)){ // <<<--- Trying to treat the OBJECT as a STRING element
      . . .
    }
    . . .
  }

To properly iterate through the contents of the file, you should utilize the FileReader helper.

For more information, refer to: Angular - Read a file and parse its content

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize TypeScript generics in Vue mixins by incorporating them into class components

After transitioning my Vue project to TypeScript, I encountered a situation that requires some management. To handle paginated tables in my application, I developed a Table mixin that manages pagination for my collection of records: @Component export defa ...

What could be causing the request parameter in my ag-grid to be undefined?

Currently experimenting with the ServerSide RowModel of Ag-Grid in combination with Angular. Planning to add server response later on, but for now focusing on familiarizing myself with the framework. Struggling to retrieve request parameter values from my ...

Animated scrolling does not function properly with external links that are fully qualified

Currently, I am working on the website julebord.bedriftsdesign.no and have added animated scroll functionality to this page: However, I have encountered a problem. The animated scroll works perfectly fine when using internal anchor links like (#myanchor). ...

What is the best way to connect a text box to a nested object in the state of a React component?

Solving a React Debugging Dilemma In my current project, I'm developing an office add-in using a React-based starter kit and TypeScript. Unfortunately, debugging has been a challenge as I am unable to access detailed error messages from React in my s ...

Create a circular modal for the design

I am interested in creating a modal that has a circular shape instead of the typical rectangle with rounded corners. This means it should appear as just a simple round container with the modal-body content in the center, without any modal-header or modal-f ...

Maintain Symbolic Links in Angular Libraries

Hey there! I'm facing an issue with creating an Angular 8 Library using ng-cli. I'm struggling to maintain symlinks when linking my external application with npm link. I attempted to modify my angular.json file like this: "build": { "bui ...

I'm struggling to change the color of a plane geometry in three.js, it always ends up black. Can anyone help me with this issue?

I'm currently working on adding a plane to the scene, and here's how I'm doing it: var plane = new THREE.Mesh(new THREE.PlaneBufferGeometry(300, 300), new THREE.MeshPhongMaterial({specular: '#fff',fog: false,color: '#ff9a0 ...

The process of including or excluding an item in an array

There are 2 toggle buttons. If the value is true, it will be added to the array, otherwise the element will be removed. data: originality: [] toggles: <toggle id='1' ref='toggleOriginal'> Click </toggle> <toggle id=&apo ...

Storing user input in an array with the use of JavaScript

Hey everyone, I'm new to JavaScript and have been struggling with a task that seems simple. I'm trying to store user input in an array and then display it in a specific div (eventually I want to create a table using the DOM and store the input th ...

Issue with file operations in Ionic1 not functioning properly after scrolling in AngularJS

Working with Ionic v1 and AngularJS, I created a file-based handheld terminal app. However, I noticed that the scroll function stopped working after performing file operations. A workaround I found is that when I click or focus on a search box, the GET re ...

Utilizing Asp.Net for Developing Microservices

Upon digesting this insightful article, I was inspired to consider transitioning our platform to a microservices architecture. Currently, our server stack consists of Asp.Net Web API (Rest...) and Angular 2 on the front end. To test the waters, I wanted ...

Organizing an angular expansion panel

I am currently dealing with an expansion panel that has a lot of content. The layout is quite messy and chaotic, as seen here: https://ibb.co/Y3z9gdf It doesn't look very appealing, so I'm wondering if there is a way to organize it better or ma ...

Utilizing Material-UI with MobileDialog HOC in TypeScript: A Beginner's Guide

I'm running into an issue while trying to implement withMobileDialog in my TypeScript code. Below is the snippet of my code, inspired by a code example from the official documentation. import withMobileDialog, { InjectedProps } from "@material-ui/co ...

"TypeScript goes bonkers with a syntax error - shouting out about an

While working on my localhost, I encountered a syntax error in the utils folder while fetching skills. Despite setting up other fetch files the same way, this one particular file is causing issues within the local host environment. You can see the error me ...

Is there a way to transfer the input value from a textfield in one component to another component in ReactJS?

I have a scenario where I need to pass the value of a text area from one component in reactjs to another. The component's value is stored using a useState hook in the first component, and I want to access it in another component to run a map() functio ...

Unable to utilize injection without the presence of an observer

Currently, I am working with typed React (TSX) and mobx for managing state. I have successfully created a component that uses both observer and inject decorators. However, I am struggling to create a component that only uses inject without observer. This ...

Difficulty in accessing JSON data with Node.js

Encountering difficulties with retrieving JSON data from a JSON file, I am faced with the following error message: "NetworkError: 404 Not Found - http://localhost:8000/channels.json" Below is the code snippet used to fetch JSON data in my HTML file: ...

How do I adjust the controls in Three.js to align with the previous camera position?

The three.js scene is equipped with W,A,S,D and left and right arrow controls, which allow for movement of the camera. However, the controls restrict the camera's movement to a fixed direction in the scene, rather than relative to its previous positio ...

Disable the default marker in Mapbox Geocoder

As a newcomer in the world of ReactJS and Mapbox GL JS, I am working on a project where I have successfully integrated a map with Geocoder, Navigation Controls, and Markers based on locations from a JSON file. However, I encountered an issue - whenever I s ...