Uploading and Parsing CSV files in Angular 2

I am new to Angular and I'm working on implementing a feature for uploading and registering content using CSV files.

Here is the code snippet:

parts.component.html

<div class="well">
  <form>
    <div class="row">
      <div class="col-md-10">
        <input class="form-control" id="file" name="file" (change)="readCsvData($event)" type="file" accept="text/plain">
      </div>
      <div class="col-md-2">
        <button class="btn btn-success" type="submit">Submit file</button>
      </div>
    </div>
  </form>
</div>

parts.component.ts

readCsvData(){
  let csvUrl = event.target;
  this.partService.upload(csvUrl)
}

part.service.ts

public upload(input: any){
    let url = this.partsUrl;
    let body = this.extractData(input);
    console.log(body);
    // return this.http.post()
  }
public extractData(data: any) {
    const file = data.files[0];
    const reader = new FileReader();
    reader.onload = function(e) {
      const content = reader.result;
      var lines = content.split("\n");
      var result = [];
      var headers = lines[0].split(",");
      for(var i = 1; i < lines.length; i++){
        var obj = {};
        var currentline = lines[i].split(",");
        for(var j = 0; j < headers.length; j++){
          obj[headers[j]] = currentline[j];
        }
        result.push(obj);
      }
      JSON.stringify(result);
    }
    reader.readAsText(file);
 }

However, the Upload function is only returning 'Undefined' in the variable 'body', when it should actually return the array of objects from the extractData function.

Any assistance or advice would be greatly appreciated!

Answer №1

Just like Rob's solution, but without the need for external libraries when performing basic string operations:

<input type="file" accept=".csv" (change)="processFile($event)">

processCsv(content){
    content.split('\n');
    // Additional desired manipulations
}

convertFile(event: any) {
  const file = event.target.files[0];
  readFileContent(file).then(content => {
    console.log('The file content as a string is: ', content);
    // Process the string further in a separate function
    this.processCsv(content)    
  }).catch(error => console.log(error))
}

readFileContent(file) {
    const reader = new FileReader()
    return new Promise((resolve, reject) => {
    reader.onload = event => resolve(event.target.result)
    reader.onerror = error => reject(error)
    reader.readAsText(file)
  })
}

Answer №2

If you're interested, check out this npm package called csvtojson.

By the way, if you're working with Angular, it's recommended to use const and let instead of var.

Here's an example of how I integrated it:

<input type="file" accept=".csv" (change)="convertFile($event)">

convertFile(event: any) {
  this.file = event.target.files[0];
  const reader = new FileReader();
  reader.readAsText(this.file);
  reader.onload = () => {
    this.textToCsv(reader.result);
  };
}

View my implementation here

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

What are the consequences of incorporating JavaScript in PHP code for changing locations?

There is a recurring question on Stack Overflow about redirecting users in PHP after input or values have been changed, and the common suggestion is to use headers for this task. However, it's important to note that headers in PHP need to be modified ...

Looking to retrieve the numerical values from a given array

I have a set of data in the following format: ['32 68', '56 78', '77 99'] I am looking to output another set of data that will consist of the sums of each pair of numbers by index using JavaScript in NodeJS. For example, [& ...

An issue arises with subdirectory URL parsing in Node.js, Express, and Ghost

Greetings and welcome to another discussion on the topic of serving Ghost on a subdirectory within a website! After following various threads and referencing this Github profile (https://github.com/owenscott/hapi-ghost-proxy-example/blob/master/config.js) ...

Received the item back from the database query

When I run the code below; var results = await Promise.all([ database.query("SELECT COUNT(amount) FROM transactions WHERE date >= now() - INTERVAL 1 DAY;"), database.query("SELECT COUNT(amount) FROM transactions WHERE date >= now() - INTER ...

What exactly do bootstrap, javascript, jquery, and ajax entail?

Exploring the world of client-side scripting to enhance web page dynamism and data collection has piqued my interest. I have come across programming languages like JavaScript, Ajax, and jQuery. However, uncertainty clouds my understanding as concepts remai ...

Using jQuery that has been installed via npm within an Express application

I recently set up a node.js + express application and utilized npm to install jQuery. Within the app.js file, I included the following code: var jquery = require('jquery'); In the header of my html file, I have incorporated JavaScript that rel ...

Enhancing TypeScript Modules

Recently, I encountered an issue with my observable extension. Everything was functioning perfectly until I updated to angular 6 and typescript 2.7.2. import { Observable } from 'rxjs/Observable'; import { BaseComponent } from './base-compo ...

The Facebook Messenger chat widget appears to be malfunctioning and failing to

https://i.sstatic.net/SZPd9.png I've gone ahead and whitelisted the domains on our Facebook page, as well as generated the chat widget. However, despite disabling all content blockers, the code seems to have no visible effect on the page. Unfortunate ...

I am facing difficulty in using Angular's ngIF directive with my object property for toggling visibility based on a condition

When writing a condition using *ngIf in my HTML code, I encountered an issue with displaying a mat-list-item based on an object property. Here is the code snippet: <mat-list-item *ngIf="object.conditionName" [ngClass]="((object.show) || i%2 != 0) ? ...

Modify a single parameter of an element in a Map

Imagine I have a map data type exampleMap: Map<string, any> The key in the map is always a string, and the corresponding value is an object. This object might look like this: { name: 'sampleName', age: 30} Now, let's say the user se ...

Form a bond with the latest SignalR library to initiate communication

After attempting to connect to an asp.net core signalR server using the code below, I encountered some issues. Can you spot where I might have gone wrong? Here is the error message that I received: Error: The "promise" option must be a Promise v ...

What is the best way to fulfill a promise after a CSV file has finished being read?

I have been utilizing the 'fast-csv' module that can be found at this link (https://www.npmjs.org/package/fast-csv), but I am open to switching to a different one. I attempted promised-csv (https://www.npmjs.org/package/promised-csv) but I had tr ...

The disappearance of hashtag (#) when passed as req.query in the backend has been observed

I am facing an issue where a string with a hashtag in the req.query is not being parsed correctly as JSON. http://localhost:3000/link/?items=[{"quantity":1,"_id":"00001","box":"item01","desc":&quo ...

AngularJS location service error

My goal is to configure the login page on my master controller so that when the username and password are both set to "admin", it will redirect me to the "/tables" path. However, every time I attempt to log in, I encounter the following error: TypeError: ...

How can I troubleshoot the issue with the Angular 6 @input() set() function not functioning properly?

After creating a component that dynamically renders buttons based on a JSON file with inputs such as disable, color, and size, I am now dealing with receiving input in the app-dynamic-form-buttons component: @Input('butnDisabled') set butnDis ...

React, incorporating emojis within a dropdown menu

Recently, I've been developing a small game using React where players can customize settings before beginning. The game involves four players chasing different tokens on the map while avoiding the player designated as "it". Within my code, I have a r ...

Retain annotations for assigned types in d.ts files

When compiling declarations for the code snippet below using Typescript v5.0.4, I encounter an issue: type SomeType<T> = { field: T; }; const getInstance = <T>( value: T ): SomeType<{ [K in keyof T]: T[K]; }> => { return { ...

Embedding an Angular 6 application as a JavaScript file in a pre-existing HTML website

Is it possible to seamlessly integrate an Angular 6 application into an existing HTML site by including it as a single JS file? Can you provide some insights on how to bundle an entire Angular App into just one JS file? Appreciate any help or tips. Thank ...

Tips on triggering an AJAX call to load additional content when a user reaches the bottom of the page for the first time

My goal is to dynamically append an HTML file to a div element when the user reaches the bottom of the page. However, I have encountered an issue where the script appends the content multiple times after refreshing the page. It seems like the Boolean varia ...

Exploring through a dynamically generated table containing JSON data

I have successfully implemented a dynamic HTML table that is populated with JSON data based on the value of a variable when the "go" button is clicked. The initial population and search functionality work flawlessly. However, I encountered an issue when ch ...