问题
I want to use a form to assign a file to a variable so that I can then post the file to my back end server.
My form looks like the following:
<form (ngSubmit)='onSubmit()' #myform='ngform'>
<div class="fileup">
<label for='file'> Upload </label>
<input id='file' type='file' name='file' [(ngModel)] = 'uploadedFile' />
<button type='submit' class='btn btn-basic'> Upload </button>
</form>
{{ uploadedFile ¦ json }}
The final line is just for development purposes and allows me to see the value of the 'uploadedFile' variable.
My in my TS file i have defined the variable simply as:
uploadedFile: any
For any type of input other than file this method works, in that, the Variable updates to show what has been entered. However for the file when I browse and select a file, the variable remains empty. I confirm this by outputting the variable 'uploadedFile' to the console when i click submit. But the variable is returned as 'undefined' even after I have selected a file. What has to be done to assign the file to this uploadedFile variable?
回答1:
You should do this:
html:
<form (ngSubmit)='onSubmit()' #myform='ngform'>
<div class="fileup">
<label for='file'> Upload </label>
<input id='file' type="file" (change)="onFileChange($event)" />
<button type='submit' [disabled]="formGroup.invalid || formGroup.prestine" class='btn btn-basic'> Upload </button>
</form>
{{ uploadedFile ¦ json }}
THen in your Component.ts
export class CustomComponent {
formGroup = this.fb.group({
file: [null, Validators.required]
});
constructor(private fb: FormBuilder, private cd: ChangeDetectorRef) {}
onFileChange(event) {
const reader = new FileReader();
if(event.target.files && event.target.files.length) {
const [file] = event.target.files;
reader.readAsDataURL(file);
reader.onload = () => {
this.formGroup.patchValue({
file: reader.result
});
// need to run CD since file load runs outside of zone
this.cd.markForCheck();
};
}
}
}
In Conclusion: every time you upload a new file you will update the FormGroup.
Here you have another example: https://medium.com/@amcdnl/file-uploads-with-angular-reactive-forms-960fd0b34cb5
来源:https://stackoverflow.com/questions/59269915/assigning-a-file-to-a-variable-using-angular-forms-and-ngmodel