Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

angular
javascript

How to upload files in Angular

Nouman Abbasi

In this shot, we will cover how to upload files using Angular.

Code

Let’s start by writing an HTML template for the upload component.

svg viewer

We define an input tag of type file and add a function to (change)-event for handling the choosing of files:

<div class="form-group">
    <label for="file">Choose File</label>
    <input type="file"
           id="file"
           (change)="handleFileInput($event.target.files)">
</div>

Next, we define a variable for the file and store it using a function:

fileToUpload: File = null;

handleFileInput(files: FileList) {
    this.fileToUpload = files.item(0);
}

Then, we define a file upload function by calling the file-upload.service:

uploadFileToActivity() {
    this.fileUploadService.postFile(this.fileToUpload).subscribe(data => {
      // do something, if upload success
      }, error => {
        console.log(error);
      });
  }

Finally, we define the file upload service. If you’re using the POST method, then you should use FormData:

postFile(fileToUpload: File): Observable<boolean> {
    const endpoint = 'your-destination-url';
    const formData: FormData = new FormData();
    formData.append('fileKey', fileToUpload, fileToUpload.name);
    return this.httpClient
      .post(endpoint, formData, { headers: yourHeadersConfig })
      .map(() => { return true; })
      .catch((e) => this.handleError(e));
}

RELATED TAGS

angular
javascript

CONTRIBUTOR

Nouman Abbasi
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring