Nearly every big project requires file upload feature. This post will show how to upload a file using services.
1. Create a file input in the template as below (restricting it to pdf files only).
2. Invoke the (change) event of the file input, get the file data and subscribe it to the ImageService.
Component
onFileChange(evt: any) { const uploadFile = evt.target.files[0]; // user cancelled selecting a file if (_.isNil(uploadFile)) { return; } const formData = new FormData(); formData.append('file', uploadFile, uploadFile.name); this.imageService.upload(formData) .subscribe( (data: any) => { this.uploaded = true; }, error => { // catch error }, () => {} ); }
3. The service that actually uploads the file to the storage server.
... @Injectable() export class ImageService { private UPLOAD_API_PATH = '/api/upload-image-service'; upload(file: any): Observable{ return this.http.post(`${this.UPLOAD_API_PATH}`, file) .map(res => res) .catch(this.handleError); } private handleError (error: any) { return Observable.throw(error); } }
Hope this is helpful to the readers.