File upload in angular 12

Today we will learn how to upload a file in angular.

Setup of file upload in angular

You can use angular CLI to create the project, install the Angular CLI, open the terminal and run the following command

  • npm install -g @angular/cli
  • Run ng new angular-file-upload command to create the angular project, whiling running the command, the terminal will ask for some featured details, by pressing enter you can choose the default settings.

You will see below the settings

ng new angular-file-upload
? Do you want to enforce stricter type checking and stricter bundle budgets in the workspace?
  This setting helps improve maintainability and catch bugs ahead of time.
  For more information, see https://angular.io/strict No

? Would you like to add Angular routing? No

? Which stylesheet format would you like to use? CSS
CREATE angular-file-upload/angular.json (3639 bytes)
CREATE angular-file-upload/package.json (1209 bytes)
CREATE angular-file-upload/README.md (1026 bytes)
CREATE angular-file-upload/tsconfig.json (538 bytes)
CREATE angular-file-upload/tslint.json (3185 bytes)
CREATE angular-file-upload/.editorconfig (274 bytes)
CREATE angular-file-upload/.gitignore (631 bytes)
CREATE angular-file-upload/.browserslistrc (703 bytes)
CREATE angular-file-upload/karma.conf.js (1436 bytes)
CREATE angular-file-upload/tsconfig.app.json (287 bytes)
CREATE angular-file-upload/tsconfig.spec.json (333 bytes)
CREATE angular-file-upload/src/favicon.ico (948 bytes)
CREATE angular-file-upload/src/index.html (303 bytes)
CREATE angular-file-upload/src/main.ts (372 bytes)
CREATE angular-file-upload/src/polyfills.ts (2830 bytes)
CREATE angular-file-upload/src/styles.css (80 bytes)
CREATE angular-file-upload/src/test.ts (753 bytes)
CREATE angular-file-upload/src/assets/.gitkeep (0 bytes)
CREATE angular-file-upload/src/environments/environment.prod.ts (51 bytes)
CREATE angular-file-upload/src/environments/environment.ts (662 bytes)
CREATE angular-file-upload/src/app/app.module.ts (314 bytes)
CREATE angular-file-upload/src/app/app.component.html (25725 bytes)
CREATE angular-file-upload/src/app/app.component.spec.ts (979 bytes)
CREATE angular-file-upload/src/app/app.component.ts (223 bytes)
CREATE angular-file-upload/src/app/app.component.css (0 bytes)
CREATE angular-file-upload/e2e/protractor.conf.js (904 bytes)
CREATE angular-file-upload/e2e/tsconfig.json (274 bytes)
CREATE angular-file-upload/e2e/src/app.e2e-spec.ts (670 bytes)
CREATE angular-file-upload/e2e/src/app.po.ts (274 bytes)
√ Packages installed successfully. 
  • cd angular-file-upload
  • Run npm start or ng serve command to run the angular App

Now you will see the below screen in your browser

angular-app-works

File upload configuration

To upload the file in angular, first, we need to design an HTML form and need to follow these steps

  • Design the HTML form
  • Handle the uploaded file in the component
  • Send the file content to the server through the HTTP client

1. Design the HTML form

In the below code, we added an input file tag and attached an event listener, on selecting the file, fileUploadInAngular() function will be called. Add the below code into your HTML template.

<!-- File name app.component.html -->
<div class="form-group">
    <label for="file">Select a file</label>
    <input type="file" (change)="fileUploadInAngular($event.target.files)">
</div>

2. Handle the uploaded file in the component

In Your component file, Define a default variable for the selected file.


/* File name app.component.ts */
selectedFile: File | null = null;

Create a function(Event handler) which you use in (change)-event of your file input tag:


/* File name app.component.ts */
fileUploadInAngular(files: FileList) {
    this.fileToUpload = files.item(0);
}

Currently, we are taking only a single file(one file at a time) If you want to handle the multifile selection, then you can iterate through this files array.

3. Send the file content to the server through the HTTP client

We have added the form and attached the file upload event listener, now we need to send that file content to the server.

You need to create an API file, that will contain all REST API calling data, let create a file-upload.service.ts

You can use below code to call your API service.

/* File name app.component.ts */
uploadFileToServer() {
    this.fileUploadService.fileUpload(this.fileToUpload).subscribe(data => {
      // do something, if upload success
      }, error => {
        console.log(error);
      });
  }

You can call the uploadFileToServer with the click of the submit button or you can call as per your use-case like call just after the file selection. so this function will call your fileUpload function from fileUploadService service. Either you can call the SERVER API from your component or you can call it from the API service file.

Add below code in file-upload.service.ts (You can call it in your app-component.ts file as well )

/* File name file-upload.service.ts */

fileUpload(fileToUpload: File): Observable<boolean> {
    const endpoint = 'SERVER URL';
    const formData: FormData = new FormData();

    formData.append('uploaded-file', fileToUpload, fileToUpload.name);
    
    return this.httpClient
      .post(endpoint, formData, { headers: yourHeadersConfig })
      .map(() => { return true; })
      .catch((e) => this.handleError(e));
}

in the fileUpload function we are appending the uploaded file content and sending it to the server API.

Conclusion

So we created an HTML form and added a file input button, once you select the file, fileUploadInAngular function will be called and the file will be uploaded to the server. Please give it a try and let me know if you need any help. Thanks


Related blog of angular


Designed with BootstrapMade & Built with Next.Js