1

Here we need to Add Test case, For that we need to upload a file using input type file using angular 6 in reactive Forms. while Uploading a file and sending as response to API,we are getting Response in the headers as

test_template: "C:\fakepath\Copy of Task_angular_issue and change_logs.xlsx"

But in the response we are getting as

{
  "Status": "Error",
  "Message": "Following parameter(s) are missing: test_script,test_template",
  "Result": []
}

Can, I know how to upload a file

html file

<div class="dashboard">
  <form class="example-form" [formGroup]="userForm" (ngSubmit)="addAutomationCase(this.login_type)">
    <div class="example-full-width" style="display: inline-block">
      <label>Template Upload</label>
      <input type="file" formControlName="test_template" accept=".xlsx,.xls" (change)="onSelectFile($event)" #fileInput>
    </div>

    <div class="dashboardFooter">
      <button type="submit" class="button btn-primary" mat-raised-button mat-button color="primary"> Save </button>
      <button type="reset" class="button btn-default" mat-raised-button mat-button color="default" [routerLink]="['/auth/admin/Manage_Automation']"> Cancel </button>
    </div>
  </form>

</div>

ts file

import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import {FormControl, FormGroupDirective,FormGroup, NgForm, Validators, FormBuilder} from '@angular/forms';
import {ErrorStateMatcher} from '@angular/material/core';

import {ActivatedRoute, Router} from "@angular/router";

import { AutomationCaseServiceProvider } from "../../../services/automationCase-service";
import { AuthServiceProvider } from "../../../services/auth-service";
import {MatSnackBar} from '@angular/material';
import { FilterTableComponent } from '../../../tables/filter-table/filter-table.component';

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const isSubmitted = form && form.submitted;
    return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
  }
}

@Component({
  selector: 'app-add-automation',
  templateUrl: './add-automation.component.html',
  styleUrls: ['./add-automation.component.scss'],
  providers: [ AutomationCaseServiceProvider, AuthServiceProvider]
})
export class AddAutomationComponent implements OnInit {


  account: { test_template: string } = {
    test_template: ''
  };

  userForm: FormGroup;

  constructor(private formBuilder: FormBuilder,
    private router: Router,
    public authService: AuthServiceProvider,
    public automationCaseService: AutomationCaseServiceProvider,
    public snackBar: MatSnackBar) {

  }

  ngOnInit() {

   **Initialize the Form Here**

    this.buildForm();

  }


  buildForm(): void {



    this.userForm = this.formBuilder.group({
        'test_template': ['', Validators.required]
      })
      console.log(this.userForm);
  };

  addAutomationCase() {
        if (!this.userForm.valid) {
          return;
        }
        else {
            this.automationCaseService.addautomationCase(this.userForm.value).subscribe(
              (resp) => {
                let UserData = JSON.stringify(resp);
                let data = JSON.parse(UserData);

                console.log(data.Message);
                if(data.Status == "Error"){
                  this.snackBar.open(data.Message,'Close', {
                    duration: 2000
                  });
                }

                else if(data.Status == "Success"){
                  this.snackBar.open(data.Message,'Close', {
                    duration: 2000
                  });
                this.router.navigate(['/auth/admin/Manage_Automation']);
                }
          });
      }
  }

  onSelectFile(event) {
    // console.log(JSON.stringify(event.target));
    // if (event.target && event.target[0]) {
    //   var reader = new FileReader();
    //   reader.readAsDataURL(event.target[0]); 
    //   // read file as data url
    //   alert(event.target.files[0]);
    // }
    let fileList: FileList = event.target.files;
    if(fileList.length > 0){
      var reader = new FileReader();
      reader.readAsDataURL(event.target.files[0]);
      console.log(event.target.files[0].name);
    }
    this.test_template = event.target.files[0].name;



          // need to run CD since file load runs outside of zone
          //this.cd.markForCheck()
  }

  onSelectscript(event) {
    if (event.target.files && event.target.files[0]) {
      var reader = new FileReader();
      reader.readAsDataURL(event.target.files[0]); // read file as data url
    }
  }

  matcher = new MyErrorStateMatcher();

}
3
  • Your APi tells you Following parameter(s) are missing: test_script,test_template, so maybe add them ? Commented Feb 18, 2019 at 10:55
  • I am Already Sending in the response to the headers{"test_template":"C:\\fakepath\\Copy of Task_angular_issue and change_logs.xlsx"} Commented Feb 18, 2019 at 10:57
  • Well apparently not ! First of all in your code it is missing test_script. Second, you have a test_template value in your form, but you edit your component object, then you send your form value through your service. Your code is full of inconsistency, and without a minimal reproducible example no-one will be able to help you. Commented Feb 18, 2019 at 11:00

1 Answer 1

1

You can upload a file in angular reactive form by importing RxFormBuilder from @rxweb/reactive-form-validators, Create its object and use toFormData() method that will convert the json data to formData, Here i have passed a link of api on the server side for your reference, it will pass the fileObject to the server. When you add [writeFile]="true" in the html, you dont need to call onSelectFile($event)

Component.ts:

export class AddAutomationComponent implements OnInit {
   api:string = 'api/User'

  account: { test_template: string } = {
    test_template: ''
  };

  userForm: RxFormGroup;

  constructor(private formBuilder: RxFormBuilder,private http: HttpClient ) {

  }

  ngOnInit() {
    this.buildForm();
  }


  buildForm(): void {
    this.userForm = <RxFormGroup>this.formBuilder.group({
        'test_template': ['', Validators.required]
      })
     let formdata = this.userForm.toFormData()
       this.http.post(this.api, formdata); // This is fake uri, This is just for your reference.
  };
}

and in the component.html:

<div class="dashboard">
  <form class="example-form" [formGroup]="userForm" (ngSubmit)="addAutomationCase(this.login_type)">
    <div class="example-full-width" style="display: inline-block">
      <label>Template Upload</label>
      <input type="file" formControlName="test_template" accept=".xlsx,.xls" [writeFile]="true">
    </div>

    <div class="dashboardFooter">
      <button type="submit" class="button btn-primary" color="primary"> Save </button>
      <button type="reset" class="button btn-default" color="default"> Cancel </button>
    </div>
  </form>

</div>

Stackblitz

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.