Angular 4 – Uploading files

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.

Add a Comment

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image