Javascript required
Skip to content Skip to sidebar Skip to footer

Part 8- How to Upload Files With Angularjs and Asp.net Mvc Application

Part 8 - How to upload files with AngularJS and ASP.NET MVC awarding.

INTRODUCTION

Part eight - How to upload files with AngularJS and ASP.Net MVC application.
The file input type not support 2 manner binding, and so we demand to find own solution for file uploads with AngularJS. Here In this example I would similar to how to upload files with AngularJS and ASP.Cyberspace MVC awarding.

STEPS :

STEP-1: CREATE Table(S) INTO THE DATABASE.

Open up Database > Correct Click on Table > Add New Table > Add Columns > Salvage > Enter table proper name > Ok.

In this example, I have used two tables every bit below

Pace-2: UPDATE ENTITY DATA MODEL.

Go to Solution Explorer > Open your Entity Data Model (hither "MyModel.edmx") > Right Click On Blank area for Get Context Carte > Update Model From Database... > A popup window will come (Entity Information Model Wizard) > Select Tables > Finish.

STEP-3: Add A FOLDER FOR Salvage UPLOADED FILES.

Go to Solution Explorer > Correct Click on the projection > Add > New Binder > Enter Folder Name
Here I have named the folder "UploadedFiles".

Step-4: ADD NEW Activity INTO YOUR CONTROLLER (Hither IN THE DATA CONTROLLER) FOR UPLOAD FILE AND SAVE Data TO THE DATABASE.

Here I have added "SaveFiles" Activeness into "DataController". Please write this following code

            
  1. [ HttpPost ]
  2. public JsonResult SaveFiles ( string description )
  3. {
  4. cord Message , fileName , actualFileName ;
  5. Message = fileName = actualFileName = string . Empty ;
  6. bool flag = false ;
  7. if ( Request . Files != null )
  8. {
  9. var file = Request . Files [ 0 ];
  10. actualFileName = file . FileName ;
  11. fileName = Guid . NewGuid () + Path . GetExtension ( file . FileName );
  12. int size = file . ContentLength ;
  13. try
  14. {
  15. file . SaveAs ( Path . Combine ( Server . MapPath ( "~/UploadedFiles" ), fileName ));
  16. UploadedFile f = new UploadedFile
  17. {
  18. FileName = actualFileName ,
  19. FilePath = fileName ,
  20. Description = clarification ,
  21. FileSize = size
  22. };
  23. using ( MyDatabaseEntities dc = new MyDatabaseEntities ())
  24. {
  25. dc . UploadedFiles . Add together ( f );
  26. dc . SaveChanges ();
  27. Message = "File uploaded successfully" ;
  28. flag = true ;
  29. }
  30. }
  31. take hold of ( Exception )
  32. {
  33. Message = "File upload failed! Please endeavor again" ;
  34. }
  35. }
  36. return new JsonResult { Data = new { Message = Message , Status = flag } };
  37. }

STEP-five: Add A NEW JS FILE FOR Add A NEW ANGULARJS CONTROLLER AND A Factory

Get to Solution Explorer > Right Click on folder (where you want to saved your AngularJS controller files, here I have created a folder named "AngularController"  under Scripts Binder) > Add together > Select Javascript file > Enter name > Add.

Write following code in this file.

            
  1. athwart . module ( 'MyApp' ) // extending angular module from first part
  2. . controller ( 'Part8Controller' , function ( $scope , FileUploadService ) {
  3. // Variables
  4. $scope . Message = "" ;
  5. $scope . FileInvalidMessage = "" ;
  6. $scope . SelectedFileForUpload = null ;
  7. $telescopic . FileDescription = "" ;
  8. $scope . IsFormSubmitted = false ;
  9. $scope . IsFileValid = false ;
  10. $scope . IsFormValid = false ;
  11. //Form Validation
  12. $scope . $lookout man ( "f1.$valid" , role ( isValid ) {
  13. $telescopic . IsFormValid = isValid ;
  14. });
  15. // THIS IS REQUIRED AS File Control is not supported 2 way bounden features of Athwart
  16. // ------------------------------------------------------------------------------------
  17. //File Validation
  18. $scope . ChechFileValid = office ( file ) {
  19. var isValid = false ;
  20. if ( $telescopic . SelectedFileForUpload != null ) {
  21. if (( file . type == 'image/png' || file . type == 'prototype/jpeg' || file . blazon == 'prototype/gif' ) && file . size <= ( 512 * 1024 )) {
  22. $telescopic . FileInvalidMessage = "" ;
  23. isValid = truthful ;
  24. }
  25. else {
  26. $scope . FileInvalidMessage = "Selected file is Invalid. (just file type png, jpeg and gif and 512 kb size allowed)" ;
  27. }
  28. }
  29. else {
  30. $scope . FileInvalidMessage = "Prototype required!" ;
  31. }
  32. $telescopic . IsFileValid = isValid ;
  33. };
  34. //File Select upshot
  35. $telescopic . selectFileforUpload = role ( file ) {
  36. $scope . SelectedFileForUpload = file [ 0 ];
  37. }
  38. //----------------------------------------------------------------------------------------
  39. //Save File
  40. $telescopic . SaveFile = function () {
  41. $scope . IsFormSubmitted = truthful ;
  42. $telescopic . Message = "" ;
  43. $telescopic . ChechFileValid ( $scope . SelectedFileForUpload );
  44. if ( $scope . IsFormValid && $telescopic . IsFileValid ) {
  45. FileUploadService . UploadFile ( $scope . SelectedFileForUpload , $scope . FileDescription ). then ( office ( d ) {
  46. alarm ( d . Bulletin );
  47. ClearForm ();
  48. }, function ( e ) {
  49. alert ( e );
  50. });
  51. }
  52. else {
  53. $scope . Message = "All the fields are required." ;
  54. }
  55. };
  56. //Clear form
  57. function ClearForm () {
  58. $scope . FileDescription = "" ;
  59. //equally ii style binding non support for File input Type so we have to articulate in this way
  60. //you tin select based on your requirement
  61. angular . forEach ( athwart . element ( "input[type='file']" ), function ( inputElem ) {
  62. angular . element ( inputElem ). val ( zippo );
  63. });
  64. $telescopic . f1 . $setPristine ();
  65. $scope . IsFormSubmitted = imitation ;
  66. }
  67. })
  68. . manufactory ( 'FileUploadService' , office ( $http , $q ) { // explained abour controller and service in role ii
  69. var fac = {};
  70. fac . UploadFile = function ( file , description ) {
  71. var formData = new FormData ();
  72. formData . append ( "file" , file );
  73. //We can send more data to server using append
  74. formData . suspend ( "description" , clarification );
  75. var defer = $q . defer ();
  76. $http . post ( "/Information/SaveFiles" , formData ,
  77. {
  78. withCredentials : true ,
  79. headers : { 'Content-Type' : undefined },
  80. transformRequest : angular . identity
  81. })
  82. . success ( function ( d ) {
  83. defer . resolve ( d );
  84. })
  85. . fault ( office () {
  86. defer . reject ( "File Upload Failed!" );
  87. });
  88. return defer . promise ;
  89. }
  90. return fac ;
  91. });

Here I accept created an angularcontroller named "Part8Controller" and aManufacturing plant named "FileUploadService" with$http injected service. I have explained a piffling about AngularJS controller , about Factory  and about $http

STEP-6: Add together NEW Activeness INTO YOUR CONTROLLER (Here IN THE HOMECONTROLLER) FOR GET THE VIEW FOR UPLOAD FILE & SAVE DATA.

Here I have added "Part8" Activity into "Habitation" Controller. Please write this following code

            
  1. public ActionResult Part8 () // Upload File with Data
  2. {
  3. render View ();
  4. }

Footstep-vii: ADD VIEW FOR THE ACTION & Design.

Right Click on Activeness Method (here right click on Part8 activeness) > Add View... > Enter View Name > Select View Engine (Razor) > Add.
Complete View

            
  1. @{
  2. ViewBag . Title = "Part8" ;
  3. }
  4. <h2> Part8 - Upload file using Angular JS </ h2 >
  5. < div ng - controller = "Part8Controller" >
  6. < form novalidate proper name = "f1" ng - submit = "SaveFile()" >
  7. < div way = "color: red" >{{ Message }}</ div >
  8. <table>
  9. <tr>
  10. <td> Select File : </ td >
  11. <td>
  12. < input type = "file" name = "file" accept = "paradigm/*" onchange = "angular.element(this).scope().selectFileforUpload(this.files)" required />
  13. < bridge class = "error" ng - show = "(f1.file.$dirty || IsFormSubmitted) && f1.file.$mistake.required" > Prototype required !</ span >
  14. < bridge class = "error" >{{ FileInvalidMessage }}</ span >
  15. </ td >
  16. </ tr >
  17. <tr>
  18. <td> Clarification : </ td >
  19. <td>
  20. < input type = "text" name = "uFileDescription" ng - model = "FileDescription" class = "{{(IsFormSubmitted?'ng-dirty' + (f1.uFileDescription.$invalid?' ng-invalid':''):'')}}" autofocus />
  21. </ td >
  22. </ tr >
  23. <tr>
  24. <td> </ td >
  25. <td>
  26. < input type = "submit" value = "Upload File" />
  27. </ td >
  28. </ tr >
  29. </ table >
  30. </ form >
  31. </ div >
  32. @department Scripts {
  33. < script src = "~/Scripts/AngularController/Part8Controller.js" ></ script >
  34. }

Pace-8: RUN APPLICATION.

amiesseciplaccont.blogspot.com

Source: http://shiva0shukla.blogspot.com/2015/05/how-to-upload-files-with-angularjs-and.html