Image Upload In Angular 5 Made Easy

Posted By : Milind Ahuja | 28-Jun-2018

There are basically 2 ways to upload the  file in Angular:

1. Choose a file, and

2. sending it to the server

 

Choose a File:

To choose a file, we require input type field Angular HTML document. The key part in this is to respond to the file changes made by the user. A change happens if the user chooses a file which is different from the current selected or the previously selected file.(initally it is null)

We can fire an event on change like this:


 

In the TypeScript file of that component, we could receive the file in the following way:

export class MyFileUploadComponent {
  onFileChanged(event) {
    const file = event.target.files[0]
  }
}

 

If you want to do it in a more advanced way in which you'd hide the file picker, you could execute the following code in your html template:


 

You would also need an extra button to proceed with the uploading process.


 

Following code you will have to add now in your component.ts file:

export class MyFileUploadComponent {
  selectedFile: File;

  onFileChanged(event) {
    this.selectedFile = event.target.files[0]
  }

  onUpload() {
    // upload code goes here
  }
}

 

Send the File to server:

Now, we have the file and we want to send it to the server, for that we need to use the Angular HttpClient.

We can send the file in two ways: either as a binary or as FormData object.

Send as binary data
onUpload() {
  // this.http is the injected HttpClient
  this.http.post('my-backend.com/file-upload', this.selectedFile)
    .subscribe(...);
}

 

Send as FormData
onUpload() {
  // this.http is the injected HttpClient
  const uploadData = new FormData();
  uploadData.append('myFile', this.selectedFile, this.selectedFile.name);
  this.http.post('my-backend.com/file-upload', uploadData)
    .subscribe(...);
}

 

Listen to upload progress

In both above cases, you can edit the above code to listen to the progress of upload:

onUpload() {
  ...
  this.http.post('my-backend.com/file-upload', uploadData, {
    reportProgress: true,
    observe: 'events'
  })
    .subscribe(event => {
      console.log(event); // handle event here
    });
}

 

THANKS.

About Author

Author Image
Milind Ahuja

Milind is a bright Lead Frontend Developer and have knowledge of HTML, CSS, JavaScript, AngularJS, Angular 2+ Versions and photoshop. His hobbies are learning new computer techniques, fitness and interest in different languages.

Request for Proposal

Name is required

Comment is required

Sending message..