Мне объяснили (здесь, между прочим), что с помощью ViewChild я мог получить доступ к NgForm, его данным и иметь возможность изменять его перед отправкой. Итак, у меня есть следующий код:
@ViewChild('frmRegister',{static:true}) registerform: NgForm;
onRegister(form):void{
this.authService.register(form.value).subscribe(res =>{
this.router.navigateByUrl('/');
})
}
async file2Base64(archivo, origen) {
const file = archivo.target.files[0];
this.file2Base64result = await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
if (origen == "avatar") this.registerform.value.avatar = this.file2Base64result;
if (origen == "signature") this.registerform.value.signature = this.file2Base64result;
}
и html выглядит так:
<form #frmRegister="ngForm" class="login-container" (ngSubmit)="onRegister(registerform)">
//part of form
<p><label name="signature">Firma Personal [PNG]</label>
<input type="file" name="signature" placeholder="Firma Personal" ngModel (change)="file2Base64($event, 'signature')"></p>
<p><label>Avatar</label>
<input type="file" name="avatar" placeholder="Avatar" ngControl="avatar" ngModel (change)="file2Base64($event, 'avatar')"></p>
<p><input type="submit" [disabled]="frmRegister.invalid" value="Register"></p>
</form>
Как видите, при изменении входного файла вызывается file2Base64. Он должен получить файл и преобразовать его в строку base 64. Однако при отправке на сервер отправляется значение по умолчанию «C: / fakepath / image.png». Независимо от того, что я делаю, значение по умолчанию перезаписывает значение, которое я пытаюсь перезаписать, то есть строку base64.