upload multipart file in angular

Upload Multipart File In Angular

In this short post, we will learn to upload a multipart file using angular.

1. Create an input field In your file.component.ts file

<div class="form-group">
    <label for="file">Choose File</label>
    <input type="file" id="file" class="file-input" accept=".png, .jpg, .jpeg" (change)="onFileSelected($event.target.files)" />

2. Upload handling in typescript

Define global variable. For example:-

fileToUpload: File | null = null;

Create a method that will be triggered when the user selects a file.

onFileSelected(event: FileList) {
    this.fileToUpload = event.item(0);

Now prepare to set the file in the multipart format and send in the API URL request to save the file.

onSaveFile() {
   const formData: FormData = new FormData();
   formData.append('file', this.fileToUpload);
   return this.httpClient.post(YOUR_API_URL, formData);

Note:- If you want to convert the uploaded image into Base64 encoded format then you can use:

getBase64(file: Blob) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);

On File upload, you can pass your file into the above method as a parameter, and will return the encoded value in base64 format in which you can set your variable and send as per the required format during the API call.

this.file = await this.getBase64(YOUR_FILE).then();

Remember to use await because the method you are using must be async.

3. Conclusion

In this post, we learned to upload the Multipart File in Angular Project. If you want to integrate it with REST API then you can take a reference to multipart file upload Spring Boot.

You can find the complete example code in the Github repository.

If you have any queries please feel free to ask.

Thank you 🙂

Notify of
Inline Feedbacks
View all comments