Here is an example, which i use to upload files to API via FormData.
In your service file like upload.service.ts
you need to create function to upload files via POST method. Here is an example for this function:
getUploadHeaders() {
let headers = new Headers({'Accept': 'application/json'});
headers.delete('Content-Type');
return headers;
}
addNewPost(newPost: FormData): Observable<FormData> {
const endpoint = 'https://yourApiUrl.com';
return this.http
.post(endpoint, newPost, { headers: this.getUploadHeaders() })
.catch((e) => this.handleError(e));
}
And now you should create upload function in your component, for example upload.component.ts
. Here is an example for upload function with FormData.
fileToUpload: File = null;
constructor(private uploadService: UploadService) { }
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}
saveFileToApi() {
const saveForm: FormData = new FormData();
if (this.fileToUpload) {
saveForm.append('fileFieldNameOnYourApi', this.fileToUpload, this.fileToUpload.name);
}
this.uploadService.addNewPost(saveForm).subscribe(() => {
console.log('Upload success!');
}, error => {
console.log('Upload failed!');
});
}
For uploading an file via FormData you need 3 parameters: propertyName on API endpoint, file and name of this file.
And in your upload.component.html
you need to have form like this one:
<form (ngSubmit)="onSubmit()">
<label for="fileField">Chose file to upload</label>
<input type="file"
id="fileField"
name="fileField"
(change)="handleFileInput($event.target.files)">
<button type="submit">Speichern</button>
</form>
For more detail of FormData read this and for more information about FormData.append() read this.