Reputation: 121
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 searched around, but I couldn't find a solution on how to add a form data to the post request using HttpClient
?
Here's 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)
Any ideas on what to try next?
Upvotes: 12
Views: 24045
Reputation: 1344
UPDATE: It's important to do not set the 'Content-Type' header, because the navigator will set it automatically based on the FormData you have created; otherwise, it'll not work properly.
Example of Content-Type auto-generated:
content-type: multipart/form-data; boundary=----WebKitFormBoundaryglPFUvMDIrKwHaRK
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 });
}
}
Upvotes: 30