Introduction
Let's learn the process of uploading and downloading the file in an Angular 9 Web Application using Web API with a back-end of the SQL Server database. After uploading the file, it will display in the UI. A Web API is used to provide data connectivity between the database and the front-end application. Here, we will upload an image and doc file and download both files.
I'm using Visual Studio Code as a tool to build my application. If you don't have Visual Studio Code, you have to download and install it first. Here is the Visual Studio Code download link:
Download Visual Studio Code Editor.
You can read my previous articles related to Angular from the following links:
First, take a look at our output:
Step 1 - Create a Database Table
Create a database. Open SQL Server and create a new database table. As you can see from the following image, I have created a database table called File Details with 4 columns.
Set Identity to true:
Step 2 - Create a Web API Project
Open Visual Studio and click on create a new project:
Select ASP.NET Web Application and click on Next:
Now give the project a name and click on the create button:
Select Web API.
Step 3 - Add ADO.NET Entity Data Model
Now, select the Models folder and right-click. Then, go to Add >> New Item >> select Data in left panel >>ADO.NET Entity Data Model.
Click Add
Click Next
Give the server the name of the SQL server and its credential, then select the database and test connection, then click the ok button.
Click Next button.
Select the UserDetails table and click Finish.
Step 4 - Add API controller
Go to the Controller folder in your API application and right-click >> Add >> Controller.
Select Web API 2 Controller-Empty.
Click on Add button
Step 5
Write the logic for uploading and downloading the file.
Step 6 - Create an Angular application for building the UI Application
Now, let's create the web application in Angular 9 that will consume the Web API.
First, we have to make sure that we have Angular CLI installed.
Open the command prompt and type the below code and press ENTER.
npm install -g @angular/cli
Now, open the Visual Studio Code and create a project.
Open TERMINAL in Visual Studio Code and type the following syntax to create a new project. Let us name it FileUploading.
ng new FileUploading
After that, hit ENTER. It will take a while to create the project.
Once created, the project should look like this.
Step 7 - Installing file-server
FileSaver.js is the solution to saving files on the client-side, and is perfect for web apps that generate files on the client.
For more details, check this
doc.
Open TERMINAL in Visual Studio Code and type the following syntax to create a new project.
npm i file-saver
Step 8 - Create a component and service
Now, we will create components to provide UI.
I'm going to create a new component, UploadDownload.
Go to the TERMINAL and go our angular project location using the following command:
cd projectName
Now, write the following command that will create a component.
ng g c UploadDownload
Press ENTER.
Now, we create a model class a create a service.
ng g s service/file
Step 9 - Install bootstrap
Now, we will install bootstrap to build a beautiful UI of our Angular application.
npm install bootstrap --save
Step 10
Add a library in the app.module.
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
- import { AppRoutingModule } from './app-routing.module';
- import { AppComponent } from './app.component';
- import {ReactiveFormsModule} from '@angular/forms';
- import { UploadDownloadComponent } from './upload-download/upload-download.component';
- import { HttpClientModule } from '@angular/common/http';
-
- @NgModule({
- declarations: [
- AppComponent,
- UploadDownloadComponent
- ],
- imports: [
- BrowserModule,
- AppRoutingModule,
- ReactiveFormsModule,
- HttpClientModule
- ],
- providers: [],
- bootstrap: [AppComponent]
- })
- export class AppModule { }
Step 11
Write typescript code in service:
- import {
- Injectable
- } from '@angular/core';
- import {
- Observable
- } from 'rxjs';
- import {
- HttpClient,
- HttpHeaders
- } from '@angular/common/http';
- @Injectable({
- providedIn: 'root'
- })
- export class FileService {
- url = 'https://localhost:44316/API/Demo';
- constructor(private http: HttpClient) {}
- public downloadFile(docFile: string): Observable < Blob > {
- return this.http.get(this.url + '/GetFile?docFile=' + docFile, {
- responseType: 'blob'
- });
- }
- public downloadImage(image: string): Observable < Blob > {
- return this.http.get(this.url + '/GetImage?image=' + image, {
- responseType: 'blob'
- });
- }
- public getFiles(): Observable < any[] > {
- return this.http.get < any[] > (this.url + '/GetFileDetails');
- }
- AddFileDetails(data: FormData): Observable < string > {
- let headers = new HttpHeaders();
- headers.append('Content-Type', 'application/json');
- const httpOptions = {
- headers: headers
- };
- return this.http.post < string > (this.url + '/AddFileDetails/', data, httpOptions);
- }
- }
Step 12 - Write HTML code in the upload-download.component
Open the upload-download.component.ts and write the below code.
- import {
- Component,
- OnInit,
- ViewChild
- } from '@angular/core';
- import {
- saveAs as importedSaveAs
- } from "file-saver";
- import {
- FileService
- } from '../Service/file.service';
- import {
- Validators,
- FormBuilder
- } from '@angular/forms';
- @Component({
- selector: 'app-upload-download',
- templateUrl: './upload-download.component.html',
- styleUrls: ['./upload-download.component.css']
- })
- export class UploadDownloadComponent implements OnInit {
- @ViewChild('resumeInput', {
- static: true
- }) resumeInput;
- @ViewChild('logoInput', {
- static: true
- }) logoInput;
- selectedFile: File = null;
- imageUrl: string;
- fileToUpload: File = null;
- saveFileForm: any;
- lstFileDetails: any;
- constructor(private service: FileService, private formBuilder: FormBuilder) {}
- ngOnInit(): void {
- this.imageUrl = './assets/blank-profile.png';
- this.saveFileForm = this.formBuilder.group({
- UserName: ['', [Validators.required]]
- });
- this.service.getFiles().subscribe(result => {
- this.lstFileDetails = result;
- })
- }
- downloadDocFile(data) {
- const DocFileName = data.DocFile;
- var DocFile = DocFileName.slice(0, -5);
- this.service.downloadFile(DocFile).subscribe((data) => {
- importedSaveAs(data, DocFile)
- });
- }
- onSelectFile(file: FileList) {
- this.fileToUpload = file.item(0);
- var reader = new FileReader();
- reader.onload = (event: any) => {
- this.imageUrl = event.target.result;
- }
- reader.readAsDataURL(this.fileToUpload);
- }
- downloadImage(data) {
- const ImageName = data.ImageName;
- var image = ImageName.slice(0, -4);
- this.service.downloadImage(image).subscribe((data) => {
- importedSaveAs(data, image)
- });
- }
- onExpSubmit() {
- debugger;
- if (this.saveFileForm.invalid) {
- return;
- }
- let formData = new FormData();
- formData.append('ImageUpload', this.logoInput.nativeElement.files[0]);
- formData.append('FileUpload', this.resumeInput.nativeElement.files[0]);
- formData.append('UserName', this.saveFileForm.value.UserName);
- this.service.AddFileDetails(formData).subscribe(result => {});
- }
- }
Now, we will write the code for the design of view page in Angular UI. Open upload-download.component.html and write the below HTML code.
- <div class="container">
- <h1>File Uploading functionality</h1>
- <br>
- <hr>
- <form [formGroup]="saveFileForm" (ngSubmit)="onExpSubmit()">
- <div class="row">
- <div class="col-md-6">
- <div class="row">
- <div class="col-md-4">
- <b>User Name</b>
- </div>
- <div class="col-md-5">
- <input type="text" formControlName="UserName" placeholder="User Name">
- </div>
- </div>
- </div>
- <div class="col-md-6">
- <div class="row">
- <div class="col-md-6">
- <b>Upload Resume</b>
- </div>
- <div class="col-md-6">
- <input type='file' #resumeInput>
- <br>
- </div>
- </div>
- </div>
- </div>
- <div class="row">
- <div class="col-md-2">
- <b>Image</b>
- </div>
- <div class="col-md-4">
- <input type='file' #logoInput (change)="onSelectFile($event.target.files)">
- <br>
- </div>
- <div class="col-md-4">
- <img [src]="imageUrl" height="100" width="120">
- </div>
- </div>
- <div class="row" align="center" style="padding-left: 400px;">
- <button type="submit" class="button" class="btn btn-primary" color="primary">Save Details
- </button>
- </div>
- </form>
- <hr>
- <div class="row">
- <table width="100%" class="responsive-table table-striped table-bordered table-hover">
- <thead>
- <tr class="btn-primary" style="height: 40px;">
- <th style="width:10%;">
- <b>User Name</b>
- </th>
- <th style="width:15%;">
- <b>File</b>
- </th>
- <th style="width:20%;">
- <b>Image</b>
- </th>
- </tr>
- </thead>
- <tbody>
- <tr *ngFor="let item of lstFileDetails">
- <td>
- <span>{{item.UserName}}</span>
- </td>
- <td>
- <span>
- <button (click)="downloadImage(item)" class="btn btn-link">
- <span>
- <img [src]="item.Image" height="60" width="60">
- </span>
- </button>
- </span>
- </td>
- <td>
- <button (click)="downloadDocFile(item)" class="btn btn-link">
- <span class="fa fa-download"> {{item.DocFile}}</span>
- </button>
- </td>
- </tr>
- </tbody>
- </table>
- <br>
- </div>
- </div>
The core functionality has almost been completed, so now go to app.component.html and set the page.
- <app-upload-download></app-upload-download>
Now, we have completed all the code functionality. Now, we will run the out project but before that, we need to set CORS because if you consume the Web API, Angular blocks the URL and we called this issue CORS(Cross OriginResource Sharing).
Step 13. Set CORS (Cross-Origin Resource Sharing)
Go to the Web API project.
Download a NuGet package for CORS. Go to NuGet Package Manager and download the following file.
After that, go to App_Start folder in Web API project and open WebApiConfig.cs class. Here, modify the Register method with the below code.
- using System.Web.Http.Cors;
After that, add the below code inside Register method.
- var cors = new EnableCorsAttribute("*", "*", "*");
- config.EnableCors(cors);
Step 14. Run
We have completed all the needed code functionality for our functionality. Before running the application, first, make sure to save your work.
Now, let's run the app and see how it works.
Open TERMINAL and write the following command to run the program.
ng serve -o
The output looks like the following image. It's a stunning UI that's been created.
Conclusion
In this article, we have learned how to perform a file upload and download operation in Angular 9 using Web API and SQL Server. We started by installing and creating the create-angular-app then used it to create our Angular application. Next, we installed file-saver bootstrap in the Angular application. After that, we created two methods for uploading images and doc files and also downloading them to the HTTP request.
I hope you enjoyed this article. I'm always willing to reply to any query or comment.