Kumar AU

Kumar AU

  • 1.4k
  • 320
  • 62.5k

this.data is always coming has ‘undefined’ file save in Angular

Nov 24 2023 9:46 PM

I am new to angular , I learned myself and implemented following code , but this.data is always shows as ‘undefined’.

 this.data is always coming has ‘undefined’ – Please let me know what mistake I am doing, 

Functionality of my code :-  It simple angular page where I upload the .csv file with 5 headers and some data in these columns in the file. After I click on upload same .csv file should be saved to server.

Below is my code, here I am passing filename and file content (in json format) to my .net webAPI, my webapi will save the file to server.

  1. Please let me know why the this.data is always shows as undefined
  2. To save the new file to server, what ever I have implemented is that correct approach ?

this is my web API code :-

public class SaveModel
{
    public string FileName { get; set; }
    public string DestinationPath { get; set; }
    public IEnumerable<string> Lines { get; set; }
}

[Route("FileSave")]
public ActionResult FileSave([FromBody] SaveModel model)
{
    try
    {
        this.SaveOperation(model.FileName, model.DestinationPath, model.Lines);
        return this.Ok();
    }
    catch (Exception ex)
    {
        this.logger.Error("File Save failed.", ex);
    }
}

public void SaveOperation(string filename, string destinationPath, IEnumerable<string> lines)
{
    StringBuilder stringBuilder = new StringBuilder();
    foreach (var line in lines)
    {
        stringBuilder.AppendLine(line);
    }

    var byteArray = Encoding.UTF8.GetBytes(stringBuilder.ToString());

    this.CreateCSVFile(destinationPath, filename, new MemoryStream(byteArray));
}

CreateCSVFile // this is my code where it calls server and place the .csv file 
        
HTML Code :

<div class="search-form">
  <mat-card>
    <div class="row">
      <div class="col-lg-1">
      </div>
      <div class="col-lg-11">
        <h2 class="font--bold">system</h2>
        <form name="#systemform" #systemform="ngForm" role="search" (ngSubmit)="UploadFile(systemform.value)" novalidate>
          <!--Start-->
          <div class="row">
            <div class="col-md-4">
              <input #fileUpload type="file" class="file-upload" name="fileUpload" id="fileUpload" accept=".xlsx,.xls,.csv" required (change)="onFileChange($event)">
              <div class="invalidFileTypeAlert" *ngIf="invalidFileType">Invalid file type. Allowed: .xlsx, .xls, .csv</div>
            </div>
            <div class="col-md-4">
              <button (click)="UploadFile(systemform.value)" type="button" mat-raised-button color="primary" [disabled]="!fileSelected">Upload</button>
              <button (click)="Reset(systemform.value)" mat-raised-button [disabled]="!fileSelected">Reset</button>
              <h5>Please upload excel file </h5>
            </div>
          </div>
        </form>
      </div>
    </div>
  </mat-card>
</div>

Below is my componenet code :- 

  /*fileName = '';*/
  fileSelected = false;
  invalidFileType = false;
  file: File = null; // Variable to store file
  data: any;
  jsonData: any;
  displayError: boolean;
  errorText: string;
  responseData: any;

  @ViewChild('fileUpload') fileUpload: ElementRef;
  /*fileName = '';*/
  fileSelected = false;
  invalidFileType = false;
  file: File = null; // Variable to store file
  data: any;
  jsonData: any;
  displayError: boolean;
  errorText: string;
  responseData: any;

  @ViewChild('fileUpload') fileUpload: ElementRef;

  Reset(form) {
    this.fileUpload.nativeElement.value = "";
    console.log("Reset completed");
  }

  UploadFile(filevalue) {

    const reqbody = {
      filename: this.file.name,
      lines: JSON.stringify(this.data)
    };

    var route = "FileSave";
    this.dataService.post(reqbody, route).subscribe(
      (data: any[]) => {
        console.log("Response data: " + data);
        LoggerService.success(`File successfully uploaded to server`, true, false);
        this.responseData = data;
      },
      (error: Response) => {
        this.displayError = true;
        this.errorText = `Error saving API service ${error.status}`;
      });
  }

  onFileChange(event: any): void {
    this.file = event.target.files[0];

         this.fileSelected = true;
        this.invalidFileType = false;
        this.readFile();
    
  }

  readFile(): void {

    fileReader.onload = (e: any) => {
      const binaryString = e.target.result;
      console.log(binaryString);
      const workBook = XLSX.read(binaryString, { type: 'binary' });

      const workSheetName = workBook.SheetNames[0];
      const workSheet = workBook.Sheets[workSheetName];

      // Parse the Excel data into JSON format
      this.data = XLSX.utils.sheet_to_json(workSheet);
      console.log(this.data);
    }
  }
}


Answers (2)