I
I
Ivan Stroykin2017-04-19 17:25:49
Angular
Ivan Stroykin, 2017-04-19 17:25:49

How to send a file along with a form (FormGroup)?

Good day,
How to send files along with the form?
There is a FormGroup

public form: FormGroup;
...
ngOnInit() {
  this.form = this.fb.group({
    ...
    file: [],
  });
}

The form has a component that implements ControlValueAccessor The component looks like this
<file fromControlName="file"></file>.
...
template: `
...
<input type="file" [(ngModel)]="value" (change)="fileChange($event)" (blur)="onBlur()">Выбрать
...
`
...
public fileChange(event) {
  let fileList: FileList = event.target.files;
  if (fileList.length > 0) {
    let file: File = fileList[0];
  }
}

And now, I can't just take and assign this.value = file.
How to approach this issue correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Stroykin, 2017-06-30
@StivinKing

What is called "The answer is on the surface" and "everything ingenious is simple." You just need to do this:

public onSubmit(value: any) {
  let params = new FormData();
  params.append('file', value.file);
  // +другие необходимые параметры
  this.testService.testRequest(params).subscribe(res => ...);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question