Я пытаюсь отправить два поля в бэкэнд-сервис.Одна - это обычная строка, а другая - файловое поле.Когда я пытаюсь использовать метод post клиента Http, я получаю 500 Ошибка от сервера, говорящую мне, что тип контента не является многокомпонентным запросом.
add-new-language.component.html
<form [formGroup]="form" (ngSubmit)="sendForm()">
<input
type="file"
formControlName="file"
(change)="onFileChanged($event)"
/>
<mat-form-field class="new-language__language-select">
<mat-select placeholder="Seleziona la lingua" formControlName="language">
<mat-option *ngFor="let lang of languages" [value]="lang.id">{{lang.label}}</mat-option>
</mat-select>
</mat-form-field>
<button mat-raised-button [disabled]="form.invalid">Upload</button>
</form>
add-new-language.component.ts
export class AddNewLanguageComponent implements OnInit {
@Input() languages: Type[];
form: FormGroup;
file: File;
constructor() {
private fb: FormBuilder;
private dictionariesService: DictionariesService;
}
ngOnInit() {
this.initForm();
}
private initForm(): void {
this.form = this.fb.group({
file: [null, Validators.required],
language: [null, Validators.required]
});
}
onFileChanged(event): void {
if (event.target.files && event.target.files.length) {
this.file = <File>event.target.files[0];
}
}
sendForm(): void {
this.dictionariesService
.saveSynonymsFile(this.form, this.file)
.subscribe(response => console.log(response));
}
}
dictionaries.service.ts
saveSynonymsFile(form: FormGroup, file: File): Observable<DictionaryFile> {
const formData = new FormData();
formData.append('lang', form.value.language);
formData.append('synonyms', file);
return this.http.post<DictionaryFile>(
`${this.querySettingsUrl}/synonyms`,
formData
);
}
Я также пытался заставить HttpHeaders использовать Content-Type: multipart / form-data, но ничего не поделать.Браузер всегда отправляет данные через Content-Type: application / json