Upload image with HttpClient : <h1>Problem</h1>

<p>I try to upload an image with angular's <a href="https://angular.io/api/common/http/HttpClient" rel="noreferrer"><code>HttpClient</code></a> to API <code>Content-Type: multipart/form-data</code> (angular v4+). Is it supported? How to do it?</p>

<p>The upload works with <code>XMLHttpRequest</code> when using module like <a href="https://github.com/ogix/ng2-fancy-image-uploader" rel="noreferrer"><code>ng2-fancy-image-uploader</code></a>. I would prefer to use a custom method with <code>HttpClient</code> which i could put into a http service together with other methods for accessing API.</p>

<h1>Here is what i have tried so far:</h1>

<h2>model.service.ts</h2>

<pre class="lang-ts prettyprint-override"><code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class ModelService {
  constructor(private http: HttpClient) { }

  public async updateAvatar(file: File): Promise&lt;void&gt; {

    // headers
    const headers = new HttpHeaders()
      .append('Content-Type', 'multipart/form-data');

    const formData: FormData = new FormData();
    formData.append('avatar', file, file.name);

    const response: HttpResponse = await this.http
      .patch('https://example.com/avatar', formData, { headers, observe: 'response' })
      .toPromise();

    console.log(response.status);
  }
}
</code></pre>

<h2>avatar-uploader.component.ts</h2>

<pre class="lang-ts prettyprint-override"><code>import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { ModelService } from './path/to/model.service';

@Component({
  selector: 'app-avatar-uploader',
  template: '&lt;input type="file" #fileInput (changes)="uploadAvatar()"&gt;'
})
export class AvatarUploaderComponent implements OnInit {

  @ViewChild('fileInput') fileInputElement: ElementRef;

  constructor() { }

  ngOnInit() { }

  public async uploadAvatar() {
    const file: File = this.fileInputElement.nativeElement.files[0];

    await this.model.updateAvatar(file);
  }

}
</code></pre>

<p>This version sends a request to (express) API, but <code>multer</code> (a library for parsing <code>multipart/form-data</code> requests) fails to parse the request.</p>

<p>So i guess i either use the <code>HttpClient</code> incorrectly, or it doesn't support <code>multipart/form-data</code> requests.</p>

<p>I guess one could send base64 encoded file or use <code>XmlHttpRequest</code>, but i ask specifically about <code>HttpClient</code>'s ability to do it.</p>
