Angular 2 - File Upload using Web API

Before moving ahead, I would highly recommend to read my previous articles which explains how to install npm and add other mandatory files

Getting Started

• Start Visual Studio.
• Create a new website.
• Provide the name and the location of website.
• Click "Next".

Here is my file upload web api code.

  1. using System.Net.Http;  
  2. using System.Web;  
  3. using System.Web.Http;  
  4. namespace FileUpload_WebAPI_Angular2.Controllers  
  5. {  
  6. public class UploadFileApiController : ApiController  
  7. {  
  8. [HttpPost]  
  9. public HttpResponseMessage UploadJsonFile()  
  10. {  
  11. HttpResponseMessage response = new HttpResponseMessage();  
  12. var httpRequest = HttpContext.Current.Request;  
  13. if (httpRequest.Files.Count > 0)  
  14. {  
  15. foreach (string file in httpRequest.Files)  
  16. {  
  17. var postedFile = httpRequest.Files[file];  
  18. var filePath = HttpContext.Current.Server.MapPath("~/UploadFile/" + postedFile.FileName);  
  19. postedFile.SaveAs(filePath);  
  20. }  
  21. }  
  22. return response;  
  23. }  
  24. }  
  25. }  

Now let’s add a new component and add web api url and provide component selector name with template url and style url

Here is my component code:

  1. import { Component } from '@angular/core';  
  2. import { Http, RequestOptions, Headers, Response } from '@angular/http';  
  3. import { Observable } from 'rxjs/Rx';  
  4. @Component({  
  5. selector: 'my-app',  
  6. templateUrl: './app/app.component.html',  
  7. styleUrls: ['./app/styles/styles.css']  
  8. })  
  9. export class AppComponent {  
  10. private isUploadBtn: boolean = true;  
  11. constructor(private http: Http) {  
  12. }  
  13. //file upload event  
  14. fileChange(event) {  
  15. debugger;  
  16. let fileList: FileList = event.target.files;  
  17. if (fileList.length > 0) {  
  18. let file: File = fileList[0];  
  19. let formData: FormData = new FormData();  
  20. formData.append('uploadFile', file, file.name);  
  21. let headers = new Headers()  
  22. //headers.append('Content-Type', 'json');  
  23. //headers.append('Accept', 'application/json');  
  24. let options = new RequestOptions({ headers: headers });  
  25. let apiUrl1 = "/api/UploadFileApi";  
  26. this.http.post(apiUrl1, formData, options)  
  27. .map(res => res.json())  
  28. .catch(error => Observable.throw(error))  
  29. .subscribe(  
  30. data => console.log('success'),  
  31. error => console.log(error)  
  32. )  
  33. }  
  34. window.location.reload();  
  35. }  
  36. }  

Here is my HTML

  1. <h2>Upload Files Sample</h2>  
  2. <div class="fileUpload btn btn-primary" *ngIf="isUploadBtn">  
  3. <span>Upload</span>  
  4. <input type="file" id="btnUpload" value="Upload" (change)="fileChange($event)" class="upload" />  
  5. </div>  
  6. <style>  
  7. #pgnumber {  
  8. display: none !important;  
  9. }  
  10. .fileUpload {  
  11. position: relative;  
  12. overflow: hidden;  
  13. margin: 10px;  
  14. }  
  15. .fileUpload input.upload {  
  16. position: absolute;  
  17. top: 0;  
  18. right: 0;  
  19. margin: 0;  
  20. padding: 0;  
  21. font-size: 20px;  
  22. cursor: pointer;  
  23. opacity: 0;  
  24. filter: alpha(opacity=0);  
  25. }  
  26. </style>  

Add component reference in app.module

  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { HttpModule } from '@angular/http';  
  5. import { AppComponent } from './app.component';  
  6. import { CommonModule, APP_BASE_HREF, LocationStrategy, HashLocationStrategy } from '@angular/common';  
  7. @NgModule({  
  8. imports: [BrowserModule, CommonModule, FormsModule, HttpModule],  
  9. declarations: [AppComponent],  
  10. providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }],  
  11. bootstrap: [AppComponent]  
  12. })  
  13. export class AppModule { };  

Now let’s add component name on index.html

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <title></title>  
  5. <base href="/">  
  6. <meta charset="utf-8" />  
  7. <meta name="viewport" content="width=device-width, initial-scale=1">  
  8. <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />  
  9. <link href="app/styles/styles.css" rel="stylesheet" />  
  10. <!-- Polyfill(s) for older browsers -->  
  11. <script src="node_modules/core-js/client/shim.min.js"></script>  
  12. <script src="node_modules/zone.js/dist/zone.js"></script>  
  13. <script src="node_modules/reflect-metadata/Reflect.js"></script>  
  14. <script src="node_modules/systemjs/dist/system.src.js"></script>  
  15. <!-- Configure SystemJS -->  
  16. <script src="systemjs.config.js"></script>  
  17. <script>  
  18. System.import('app').catch(  
  19. function (err)  
  20. { console.error(err); });  
  21. </script>  
  22. </head>  
  23. <body>  
  24. <header class="navbar navbar-inner navbar-fixed-top">  
  25. <nav class="container">  
  26. <div class="navbar-header">  
  27. <span class="app-title">Upload File Sample in Angular 2</span>  
  28. </div>  
  29. </nav>  
  30. </header>  
  31. <main class="container">  
  32. <my-app>Loading...</my-app>  
  33. </main>  
  34. </body>  
  35. </html>  

Now time to run the application to see the output


Click on upload button that will work as browse files from computer and upload in given directory in your local system.


Select image which you want upload in directory. Once upload is done go to the directory and check if the file is uploaded or not.


Conclusion

In this article, we have learned how to upload files using web api in angular 2. If you have any question or comment, drop me a comment in C# Corner comments section.

Up Next
    Ebook Download
    View all
    Learn
    View all