Я хочу загрузить файл как часть свойства к объекту в форме.Я исследовал это, но большая часть документации относится к сервисам, которые обрабатывают только файл.В моем сценарии у меня есть форма, в которой наряду с другими текстовыми входами и датчиками также есть поле загрузки файла.Так как бы вы справились с этим?
<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>
Вот сервис:
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());
}
}
API - это ядро 2 web api
Метод для захвата файлаВнутри компонента должно быть что-то вроде этого:
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]
})
};
}
}
Но как бы вы связали вложенный файл со свойством obj оставляющего приложения, чтобы передать его в целом через API?