Felice Anastasio
Felice Anastasio

Reputation: 43

Use multipart/form-data to send files in Angular 6

I try to send two fields to a backend service. One is a common string and the other is a file field. When I try to use the post method of the Http Client I recieve an 500 Error from the server telling me that the content-type is not a multipart request.

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
  );
}

I tried also to force the HttpHeaders with Content-Type: multipart/form-data but nothing to do. The browser always send the data through Content-Type: application/json

Upvotes: 1

Views: 6576

Answers (1)

Ushmi Dave
Ushmi Dave

Reputation: 286

Instead of creating service for saving file, importing RxFormBuilder from @rxweb, Create its object and use toFormData() method that will convert the json data to formData, Here i have passed a link of api on the server side for your reference, it will pass the fileObject to the server. When you add [writeFile]="true" in the html, you dont need to call onFileChanged($event)

Component.html:

export class AddNewLanguageComponent implements OnInit {
  @Input() languages: Type[];
  form: RxFormGroup;
  api:string = 'api/User'
  constructor(private fb: RxFormBuilder,private http: HttpClient) {}

  ngOnInit() {
    this.initForm();
  }

  private initForm(): void {
    this.form = <RxFormGroup>this.fb.group({
      file: [null, Validators.required],
      language: [null, Validators.required]
    });
  }



  sendForm(): void {
      let formdata = this.form.toFormData()
        this.http.post(this.api, formdata); // This is fake uri, This is just for your reference
  }
} 

And in the component.html :

<form [formGroup]="form" (ngSubmit)="sendForm()">
  <input
     type="file"
     formControlName="file"
     [writeFile]="true"
  />
  <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>

  <button>Upload</button> 
</form>

Stackblitz

Upvotes: 1

Related Questions