I am facing a challenge with uploading a file as part of a property to an object within a form. Most documentations I have come across only focus on services that handle standalone files. In my case, I have a form with various text inputs and date pickers, along with a file upload field. So, how can this scenario be handled effectively?
<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 being used is Core 2 Web API.
To handle the file in the component, a method like this can be implemented:
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]
})
};
}
}
However, binding the attached file to the property of the leaveapplication obj in order to pass it through to the API as a whole remains a question.