3

I want to upload a file as part of a property to an object in a form. I have researched on this but most of the documentations are referring to services which only handle a file. In my scenario I have a form in which alongside other text inputs and date pickers there is a file upload field too. So how would you deal with that?

<mat-form-field>
    <input matInput placeholder="Start date" name="startdate">
    <mat-datepicker-toggle matSuffix [for]="SDpicker"></mat-datepicker-toggle>
    <mat-datepicker #SDpicker ngDefaultControl (selectedChanged)="onStartDateChange($event)"></mat-datepicker>
  </mat-form-field>
  <mat-form-field>
    <input matInput placeholder="End date" name="enddate">
    <mat-datepicker-toggle matSuffix [for]="EDpicker"></mat-datepicker-toggle>
    <mat-datepicker #EDpicker ></mat-datepicker>
  </mat-form-field>
  <mat-form-field>
    <input matInput placeholder="No. of days" name="noofdays">
  </mat-form-field>
  <label for="uploadAttachment" class="upload-file">
    <mat-icon>cloud_upload</mat-icon>
  </label>
  <input type="file" id="leaveapplication.attachment" class="hidden-input" (change)="onFileChange($event)" accept="image/jpeg, .jpeg, image/png, .png, image/pjpeg, .jpg, application/pdf" #fileInput>
  <button mat-button (click)="clearFile()">clear file</button>

Here is the service:

import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
@Injectable()
export class LeaveapplicationService {

  constructor(private http: Http) { }
  getLeaveApplications() {
    return this.http.get('api/LeaveApplications/Get').map(res => res.json());
  }

  create(leaveapplication) {
    return this.http.post('/api/LeaveApplications', leaveapplication).map(res => res.json());
  }

}

The API is core 2 web api

The method to grab the file inside the component should be something like this:

 onFileChange(event) {
    let reader = new FileReader();
    if (event.target.files && event.target.files.length > 0) {
      let file = event.target.files[0];
      reader.readAsDataURL(file);
      reader.onload = () => {
        this.form.get('leaveapplication.attachment').setValue({
          filename: file.name,
          filetype: file.type,
          value: reader.result.split(',')[1]
        })
      };
    }
  }

But how would you bind the attached file to the property of the leaveapplication obj to pass it as a whole through to the API?

Efron A.
  • 353
  • 3
  • 10
  • 19

2 Answers2

0

You need to use formData to upload a file throught a multipart request.

public create(leaveapplication, file:File) : Observable<any>{
    let formData: FormData = new FormData();
    formData.append('data', JSON.stringify(leaveapplication));
    formData.append('file', file, file.name);
    return this.http.post('/api/LeaveApplications' , formData)
        .map(res => {return res.json()});
}

With this method, your attachment is not an attribut of 'leaveapplication' anymore.

If you really need to have your attachment as an attribut, you can try base64 encoding.

Y. Tarion
  • 433
  • 7
  • 17
-2

You need to pass the file into your object to the API as formData. Something like below.

onFileChange(event) {
    let reader = new FileReader();
    if (event.target.files && event.target.files.length > 0) {
      let file = event.target.files[0];
      const data= new Blob([file], { type: "application/text" });
      const formData = new FormData();
      formData.append("inputFile", jsonData);
      };
    }
  }