File Upload and Download in Angular 9 With Web API and SQL

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:
 
File Upload And Download In Angular 9 With Web API And SQL
 
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.
 
File Upload And Download In Angular 9 With Web API And SQL
 
Set Identity to true:
 
File Upload And Download In Angular 9 With Web API And SQL
 
Step 2 - Create a Web API Project

Open Visual Studio and click on create a new project:
 
File Upload And Download In Angular 9 With Web API And SQL
 
Select ASP.NET Web Application and click on Next:
 
File Upload And Download In Angular 9 With Web API And SQL
 
Now give the project a name and click on the create button:
 
File Upload And Download In Angular 9 With Web API And SQL
 
Select Web API.
 
File Upload And Download In Angular 9 With Web API And SQL
 
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.
 
File Upload And Download In Angular 9 With Web API And SQL
 
Click Add
 
File Upload And Download In Angular 9 With Web API And SQL
 
Click Next 
 
File Upload And Download In Angular 9 With Web API And SQL
 
Give the server the name of the SQL server and its credential, then select the database and test connection, then click the ok button.
 
File Upload And Download In Angular 9 With Web API And SQL
 
Click Next button.
 
File Upload And Download In Angular 9 With Web API And SQL
 
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.
 
File Upload And Download In Angular 9 With Web API And SQL
 
Click on Add button
 
Step 5
 
Write the logic for uploading and downloading the file.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Net;  
  6. using System.Net.Http;  
  7. using System.Net.Http.Headers;  
  8. using System.Web;  
  9. using System.Web.Http;  
  10. using FileUploadAPI.Models;  
  11. namespace FileUploadAPI.Controllers {  
  12.     [RoutePrefix("API/Demo")]  
  13.     public class DemoAPIController: ApiController {  
  14.         [HttpPost]  
  15.         [Route("AddFileDetails")]  
  16.         public IHttpActionResult AddFile() {  
  17.                 string result = "";  
  18.                 try {  
  19.                     AngularDBEntities objEntity = new AngularDBEntities();  
  20.                     FileDetail objFile = new FileDetail();  
  21.                     string fileName = null;  
  22.                     string imageName = null;  
  23.                     var httpRequest = HttpContext.Current.Request;  
  24.                     var postedImage = httpRequest.Files["ImageUpload"];  
  25.                     var postedFile = httpRequest.Files["FileUpload"];  
  26.                     objFile.UserName = httpRequest.Form["UserName"];  
  27.                     if (postedImage != null) {  
  28.                         imageName = new String(Path.GetFileNameWithoutExtension(postedImage.FileName).Take(10).ToArray()).Replace(" ""-");  
  29.                         imageName = imageName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedImage.FileName);  
  30.                         var filePath = HttpContext.Current.Server.MapPath("~/Files/" + imageName);  
  31.                         postedImage.SaveAs(filePath);  
  32.                     }  
  33.                     if (postedFile != null) {  
  34.                         fileName = new String(Path.GetFileNameWithoutExtension(postedFile.FileName).Take(10).ToArray()).Replace(" ""-");  
  35.                         fileName = fileName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedFile.FileName);  
  36.                         var filePath = HttpContext.Current.Server.MapPath("~/Files/" + fileName);  
  37.                         postedFile.SaveAs(filePath);  
  38.                     }  
  39.                     objFile.Image = imageName;  
  40.                     objFile.DocFile = fileName;  
  41.                     objEntity.FileDetails.Add(objFile);  
  42.                     int i = objEntity.SaveChanges();  
  43.                     if (i > 0) {  
  44.                         result = "File uploaded sucessfully";  
  45.                     } else {  
  46.                         result = "File uploaded faild";  
  47.                     }  
  48.                 } catch (Exception) {  
  49.                     throw;  
  50.                 }  
  51.                 return Ok(result);  
  52.             }  
  53.             [HttpGet]  
  54.             [Route("GetFile")]  
  55.         //download file api  
  56.         public HttpResponseMessage GetFile(string docFile) {  
  57.                 //Create HTTP Response.  
  58.                 HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);  
  59.                 //Set the File Path.  
  60.                 string filePath = System.Web.HttpContext.Current.Server.MapPath("~/Files/") + docFile + ".docx";  
  61.                 //Check whether File exists.  
  62.                 if (!File.Exists(filePath)) {  
  63.                     //Throw 404 (Not Found) exception if File not found.  
  64.                     response.StatusCode = HttpStatusCode.NotFound;  
  65.                     response.ReasonPhrase = string.Format("File not found: {0} .", docFile);  
  66.                     throw new HttpResponseException(response);  
  67.                 }  
  68.                 //Read the File into a Byte Array.  
  69.                 byte[] bytes = File.ReadAllBytes(filePath);  
  70.                 //Set the Response Content.  
  71.                 response.Content = new ByteArrayContent(bytes);  
  72.                 //Set the Response Content Length.  
  73.                 response.Content.Headers.ContentLength = bytes.LongLength;  
  74.                 //Set the Content Disposition Header Value and FileName.  
  75.                 response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");  
  76.                 response.Content.Headers.ContentDisposition.FileName = docFile + ".docx";  
  77.                 //Set the File Content Type.  
  78.                 response.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(docFile + ".docx"));  
  79.                 return response;  
  80.             }  
  81.             [HttpGet]  
  82.             [Route("GetFileDetails")]  
  83.         public IHttpActionResult GetFile() {  
  84.                 var url = HttpContext.Current.Request.Url;  
  85.                 IEnumerable < FileDetailsVM > lstFile = new List < FileDetailsVM > ();  
  86.                 try {  
  87.                     AngularDBEntities objEntity = new AngularDBEntities();  
  88.                     lstFile = objEntity.FileDetails.Select(a => new FileDetailsVM {  
  89.                         FileId = a.FileId,  
  90.                             UserName = a.UserName,  
  91.                             Image = url.Scheme + "://" + url.Host + ":" + url.Port + "/Files/" + a.Image,  
  92.                             DocFile = a.DocFile,  
  93.                             ImageName = a.Image  
  94.                     }).ToList();  
  95.                 } catch (Exception) {  
  96.                     throw;  
  97.                 }  
  98.                 return Ok(lstFile);  
  99.             }  
  100.             [HttpGet]  
  101.             [Route("GetImage")]  
  102.         //download Image file api  
  103.         public HttpResponseMessage GetImage(string image) {  
  104.             //Create HTTP Response.  
  105.             HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);  
  106.             //Set the File Path.  
  107.             string filePath = System.Web.HttpContext.Current.Server.MapPath("~/Files/") + image + ".PNG";  
  108.             //Check whether File exists.  
  109.             if (!File.Exists(filePath)) {  
  110.                 //Throw 404 (Not Found) exception if File not found.  
  111.                 response.StatusCode = HttpStatusCode.NotFound;  
  112.                 response.ReasonPhrase = string.Format("File not found: {0} .", image);  
  113.                 throw new HttpResponseException(response);  
  114.             }  
  115.             //Read the File into a Byte Array.  
  116.             byte[] bytes = File.ReadAllBytes(filePath);  
  117.             //Set the Response Content.  
  118.             response.Content = new ByteArrayContent(bytes);  
  119.             //Set the Response Content Length.  
  120.             response.Content.Headers.ContentLength = bytes.LongLength;  
  121.             //Set the Content Disposition Header Value and FileName.  
  122.             response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");  
  123.             response.Content.Headers.ContentDisposition.FileName = image + ".PNG";  
  124.             //Set the File Content Type.  
  125.             response.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(image + ".PNG"));  
  126.             return response;  
  127.         }  
  128.     }  
  129. }  
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.
 
File Upload And Download In Angular 9 With Web API And SQL
File Upload And Download In Angular 9 With Web API And SQL
 
Once created, the project should look like this.
 
File Upload And Download In Angular 9 With Web API And SQL
 
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
 
File Upload And Download In Angular 9 With Web API And SQL
 
Step 9 - Install bootstrap
 
Now, we will install bootstrap to build a beautiful UI of our Angular application.
 
npm install bootstrap --save
 
File Upload And Download In Angular 9 With Web API And SQL
 
Step 10
 
Add a library in the app.module.
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { AppRoutingModule } from './app-routing.module';  
  4. import { AppComponent } from './app.component';  
  5. import {ReactiveFormsModule} from '@angular/forms';  
  6. import { UploadDownloadComponent } from './upload-download/upload-download.component';  
  7. import { HttpClientModule } from '@angular/common/http';  
  8.   
  9. @NgModule({  
  10.    declarations: [  
  11.       AppComponent,  
  12.       UploadDownloadComponent  
  13.    ],  
  14.    imports: [  
  15.       BrowserModule,  
  16.       AppRoutingModule,  
  17.       ReactiveFormsModule,  
  18.       HttpClientModule  
  19.    ],  
  20.    providers: [],  
  21.       bootstrap: [AppComponent]  
  22.    })  
  23. export class AppModule { }  
Step 11
 
Write typescript code in service:
  1. import {  
  2.     Injectable  
  3. } from '@angular/core';  
  4. import {  
  5.     Observable  
  6. } from 'rxjs';  
  7. import {  
  8.     HttpClient,  
  9.     HttpHeaders  
  10. } from '@angular/common/http';  
  11. @Injectable({  
  12.     providedIn: 'root'  
  13. })  
  14. export class FileService {  
  15.     url = 'https://localhost:44316/API/Demo';  
  16.     constructor(private http: HttpClient) {}  
  17.     public downloadFile(docFile: string): Observable < Blob > {  
  18.         return this.http.get(this.url + '/GetFile?docFile=' + docFile, {  
  19.             responseType: 'blob'  
  20.         });  
  21.     }  
  22.     public downloadImage(image: string): Observable < Blob > {  
  23.         return this.http.get(this.url + '/GetImage?image=' + image, {  
  24.             responseType: 'blob'  
  25.         });  
  26.     }  
  27.     public getFiles(): Observable < any[] > {  
  28.         return this.http.get < any[] > (this.url + '/GetFileDetails');  
  29.     }  
  30.     AddFileDetails(data: FormData): Observable < string > {  
  31.         let headers = new HttpHeaders();  
  32.         headers.append('Content-Type''application/json');  
  33.         const httpOptions = {  
  34.             headers: headers  
  35.         };  
  36.         return this.http.post < string > (this.url + '/AddFileDetails/', data, httpOptions);  
  37.     }  
  38. }  
Step 12 - Write HTML code in the upload-download.component
 
Open the upload-download.component.ts and write the below code. 
  1. import {  
  2.     Component,  
  3.     OnInit,  
  4.     ViewChild  
  5. } from '@angular/core';  
  6. import {  
  7.     saveAs as importedSaveAs  
  8. } from "file-saver";  
  9. import {  
  10.     FileService  
  11. } from '../Service/file.service';  
  12. import {  
  13.     Validators,  
  14.     FormBuilder  
  15. } from '@angular/forms';  
  16. @Component({  
  17.     selector: 'app-upload-download',  
  18.     templateUrl: './upload-download.component.html',  
  19.     styleUrls: ['./upload-download.component.css']  
  20. })  
  21. export class UploadDownloadComponent implements OnInit {  
  22.     @ViewChild('resumeInput', {  
  23.         statictrue  
  24.     }) resumeInput;  
  25.     @ViewChild('logoInput', {  
  26.         statictrue  
  27.     }) logoInput;  
  28.     selectedFile: File = null;  
  29.     imageUrl: string;  
  30.     fileToUpload: File = null;  
  31.     saveFileForm: any;  
  32.     lstFileDetails: any;  
  33.     constructor(private service: FileService, private formBuilder: FormBuilder) {}  
  34.     ngOnInit(): void {  
  35.         this.imageUrl = './assets/blank-profile.png';  
  36.         this.saveFileForm = this.formBuilder.group({  
  37.             UserName: ['', [Validators.required]]  
  38.         });  
  39.         this.service.getFiles().subscribe(result => {  
  40.             this.lstFileDetails = result;  
  41.         })  
  42.     }  
  43.     downloadDocFile(data) {  
  44.         const DocFileName = data.DocFile;  
  45.         var DocFile = DocFileName.slice(0, -5);  
  46.         this.service.downloadFile(DocFile).subscribe((data) => {  
  47.             importedSaveAs(data, DocFile)  
  48.         });  
  49.     }  
  50.     onSelectFile(file: FileList) {  
  51.         this.fileToUpload = file.item(0);  
  52.         var reader = new FileReader();  
  53.         reader.onload = (event: any) => {  
  54.             this.imageUrl = event.target.result;  
  55.         }  
  56.         reader.readAsDataURL(this.fileToUpload);  
  57.     }  
  58.     downloadImage(data) {  
  59.         const ImageName = data.ImageName;  
  60.         var image = ImageName.slice(0, -4);  
  61.         this.service.downloadImage(image).subscribe((data) => {  
  62.             importedSaveAs(data, image)  
  63.         });  
  64.     }  
  65.     onExpSubmit() {  
  66.         debugger;  
  67.         if (this.saveFileForm.invalid) {  
  68.             return;  
  69.         }  
  70.         let formData = new FormData();  
  71.         formData.append('ImageUpload'this.logoInput.nativeElement.files[0]);  
  72.         formData.append('FileUpload'this.resumeInput.nativeElement.files[0]);  
  73.         formData.append('UserName'this.saveFileForm.value.UserName);  
  74.         this.service.AddFileDetails(formData).subscribe(result => {});  
  75.     }  
  76. }  
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. 
  1. <div class="container">  
  2.     <h1>File Uploading functionality</h1>  
  3.     <br>  
  4.         <hr>  
  5.             <form [formGroup]="saveFileForm" (ngSubmit)="onExpSubmit()">  
  6.                 <div class="row">  
  7.                     <div class="col-md-6">  
  8.                         <div class="row">  
  9.                             <div class="col-md-4">  
  10.                                 <b>User Name</b>  
  11.                             </div>  
  12.                             <div class="col-md-5">  
  13.                                 <input type="text" formControlName="UserName" placeholder="User Name">  
  14.                                 </div>  
  15.                             </div>  
  16.                         </div>  
  17.                         <div class="col-md-6">  
  18.                             <div class="row">  
  19.                                 <div class="col-md-6">  
  20.                                     <b>Upload Resume</b>  
  21.                                 </div>  
  22.                                 <div class="col-md-6">  
  23.                                     <input type='file' #resumeInput>  
  24.                                         <br>  
  25.                                         </div>  
  26.                                     </div>  
  27.                                 </div>  
  28.                             </div>  
  29.                             <div class="row">  
  30.                                 <div class="col-md-2">  
  31.                                     <b>Image</b>  
  32.                                 </div>  
  33.                                 <div class="col-md-4">  
  34.                                     <input type='file' #logoInput (change)="onSelectFile($event.target.files)">  
  35.                                         <br>  
  36.                                         </div>  
  37.                                         <div class="col-md-4">  
  38.                                             <img [src]="imageUrl" height="100" width="120">  
  39.                                             </div>  
  40.                                         </div>  
  41.                                         <div class="row" align="center" style="padding-left: 400px;">  
  42.                                             <button type="submit" class="button" class="btn btn-primary" color="primary">Save Details  
  43. </button>  
  44.                                         </div>  
  45.                                     </form>  
  46.                                     <hr>  
  47.                                         <div class="row">  
  48.                                             <table width="100%" class="responsive-table table-striped table-bordered table-hover">  
  49.                                                 <thead>  
  50.                                                     <tr class="btn-primary" style="height: 40px;">  
  51.                                                         <th style="width:10%;">  
  52.                                                             <b>User Name</b>  
  53.                                                         </th>  
  54.                                                         <th style="width:15%;">  
  55.                                                             <b>File</b>  
  56.                                                         </th>  
  57.                                                         <th style="width:20%;">  
  58.                                                             <b>Image</b>  
  59.                                                         </th>  
  60.                                                     </tr>  
  61.                                                 </thead>  
  62.                                                 <tbody>  
  63.                                                     <tr *ngFor="let item of lstFileDetails">  
  64.                                                         <td>  
  65.                                                             <span>{{item.UserName}}</span>  
  66.                                                         </td>  
  67.                                                         <td>  
  68.                                                             <span>  
  69.                                                                 <button (click)="downloadImage(item)" class="btn btn-link">  
  70.                                                                     <span>    
  71.                                                                         <img [src]="item.Image" height="60" width="60">  
  72.                                                                         </span>  
  73.                                                                     </button>  
  74.                                                                 </span>  
  75.                                                             </td>  
  76.                                                             <td>  
  77.                                                                 <button (click)="downloadDocFile(item)" class="btn btn-link">  
  78.                                                                     <span class="fa fa-download">  {{item.DocFile}}</span>  
  79.                                                                 </button>  
  80.                                                             </td>  
  81.                                                         </tr>  
  82.                                                     </tbody>  
  83.                                                 </table>  
  84.                                                 <br>  
  85.                                                 </div>  
  86.                                             </div>  
The core functionality has almost been completed, so now go to app.component.html and set the page. 
  1. <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.
 
File Upload And Download In Angular 9 With Web API And SQL

Add namespace
  1. using System.Web.Http.Cors;  
After that, add the below code inside Register method. 
  1. var cors = new EnableCorsAttribute("*""*""*"); //origins,headers,methods  
  2. 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.
 
File Upload And Download In Angular 9 With Web API And SQL
 

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.


Similar Articles