Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use HttpClient send a form data request?

Tags:

angular

Currently, I want to upload a file to our server. I can do it with Http from @angular/http lib.

But now, we want to change using HttpClient to align with the current project. I did search around, I could not find a solution on how to add a form data to the post request using HttpClient?

[Update] the code that i used to upload file by http let formData: FormData = new FormData(); formData.append('file', file, file.name); this._http.post(base_api_url + uploadFileApi, formData)

Could someone help me on that?

Thank so much.

like image 320
Bao Huynh Avatar asked Sep 19 '17 03:09

Bao Huynh


People also ask

What is HttpClient request?

HttpClient class provides a base class for sending/receiving the HTTP requests/responses from a URL. It is a supported async feature of . NET framework. HttpClient is able to process multiple concurrent requests. It is a layer over HttpWebRequest and HttpWebResponse.


1 Answers

Here is the Angular service to do that:

import { Injectable } from '@angular/core';

@Injectable()
export class UploadService {

  constructor(private http: HttpClient) {}

  uploadFile(file: File): Observable<any> {

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

    const headers = new HttpHeaders({ 'enctype': 'multipart/form-data' });

    return this.http.post(apiUrl, formData, { headers: headers });

  }
}
like image 161
Babak Avatar answered Oct 25 '22 17:10

Babak