Home » Featured, Headline, Software Development

Angular 4 – Uploading files

26 September 2017 No Comment

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).

<input type="file" name="uploadFile" #uploadFile placeholder="Select File to upload" (change)="onFileChange($event)" accept=".pdf">

2. Invoke the (change) event of the file input, get the file data and subscribe it to the ImageService.

  onFileChange(evt: any) {
   const uploadFile = evt.target.files[0];
    // user cancelled selecting a file
    if (_.isNil(uploadFile)) {

    const formData = new FormData();
    formData.append('file', uploadFile, uploadFile.name);
        (data: any) => {
          this.uploaded = true;
        error => {
         // catch error
        () => {}

3. The service that actually uploads the file to the storage server.

export class ImageService {
  private UPLOAD_API_PATH = '/api/upload-image-service';
  upload(file: any): Observable<any> {
    return this.http.post(`${this.UPLOAD_API_PATH}`, file)
      .map(res => res)

  private handleError (error: any) {
    return Observable.throw(error);

Hope this is helpful to the readers.

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.

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