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
- [ HttpPost ]
- public JsonResult SaveFiles ( string description )
- {
- cord Message , fileName , actualFileName ;
- Message = fileName = actualFileName = string . Empty ;
- bool flag = false ;
- if ( Request . Files != null )
- {
- var file = Request . Files [ 0 ];
- actualFileName = file . FileName ;
- fileName = Guid . NewGuid () + Path . GetExtension ( file . FileName );
- int size = file . ContentLength ;
- try
- {
- file . SaveAs ( Path . Combine ( Server . MapPath ( "~/UploadedFiles" ), fileName ));
- UploadedFile f = new UploadedFile
- {
- FileName = actualFileName ,
- FilePath = fileName ,
- Description = clarification ,
- FileSize = size
- };
- using ( MyDatabaseEntities dc = new MyDatabaseEntities ())
- {
- dc . UploadedFiles . Add together ( f );
- dc . SaveChanges ();
- Message = "File uploaded successfully" ;
- flag = true ;
- }
- }
- take hold of ( Exception )
- {
- Message = "File upload failed! Please endeavor again" ;
- }
- }
- return new JsonResult { Data = new { Message = Message , Status = flag } };
- }
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.
- athwart . module ( 'MyApp' ) // extending angular module from first part
- . controller ( 'Part8Controller' , function ( $scope , FileUploadService ) {
- // Variables
- $scope . Message = "" ;
- $scope . FileInvalidMessage = "" ;
- $scope . SelectedFileForUpload = null ;
- $telescopic . FileDescription = "" ;
- $scope . IsFormSubmitted = false ;
- $scope . IsFileValid = false ;
- $scope . IsFormValid = false ;
- //Form Validation
- $scope . $lookout man ( "f1.$valid" , role ( isValid ) {
- $telescopic . IsFormValid = isValid ;
- });
- // THIS IS REQUIRED AS File Control is not supported 2 way bounden features of Athwart
- // ------------------------------------------------------------------------------------
- //File Validation
- $scope . ChechFileValid = office ( file ) {
- var isValid = false ;
- if ( $telescopic . SelectedFileForUpload != null ) {
- if (( file . type == 'image/png' || file . type == 'prototype/jpeg' || file . blazon == 'prototype/gif' ) && file . size <= ( 512 * 1024 )) {
- $telescopic . FileInvalidMessage = "" ;
- isValid = truthful ;
- }
- else {
- $scope . FileInvalidMessage = "Selected file is Invalid. (just file type png, jpeg and gif and 512 kb size allowed)" ;
- }
- }
- else {
- $scope . FileInvalidMessage = "Prototype required!" ;
- }
- $telescopic . IsFileValid = isValid ;
- };
- //File Select upshot
- $telescopic . selectFileforUpload = role ( file ) {
- $scope . SelectedFileForUpload = file [ 0 ];
- }
- //----------------------------------------------------------------------------------------
- //Save File
- $telescopic . SaveFile = function () {
- $scope . IsFormSubmitted = truthful ;
- $telescopic . Message = "" ;
- $telescopic . ChechFileValid ( $scope . SelectedFileForUpload );
- if ( $scope . IsFormValid && $telescopic . IsFileValid ) {
- FileUploadService . UploadFile ( $scope . SelectedFileForUpload , $scope . FileDescription ). then ( office ( d ) {
- alarm ( d . Bulletin );
- ClearForm ();
- }, function ( e ) {
- alert ( e );
- });
- }
- else {
- $scope . Message = "All the fields are required." ;
- }
- };
- //Clear form
- function ClearForm () {
- $scope . FileDescription = "" ;
- //equally ii style binding non support for File input Type so we have to articulate in this way
- //you tin select based on your requirement
- angular . forEach ( athwart . element ( "input[type='file']" ), function ( inputElem ) {
- angular . element ( inputElem ). val ( zippo );
- });
- $telescopic . f1 . $setPristine ();
- $scope . IsFormSubmitted = imitation ;
- }
- })
- . manufactory ( 'FileUploadService' , office ( $http , $q ) { // explained abour controller and service in role ii
- var fac = {};
- fac . UploadFile = function ( file , description ) {
- var formData = new FormData ();
- formData . append ( "file" , file );
- //We can send more data to server using append
- formData . suspend ( "description" , clarification );
- var defer = $q . defer ();
- $http . post ( "/Information/SaveFiles" , formData ,
- {
- withCredentials : true ,
- headers : { 'Content-Type' : undefined },
- transformRequest : angular . identity
- })
- . success ( function ( d ) {
- defer . resolve ( d );
- })
- . fault ( office () {
- defer . reject ( "File Upload Failed!" );
- });
- return defer . promise ;
- }
- return fac ;
- });
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
- public ActionResult Part8 () // Upload File with Data
- {
- render View ();
- }
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
- @{
- ViewBag . Title = "Part8" ;
- }
- <h2> Part8 - Upload file using Angular JS </ h2 >
- < div ng - controller = "Part8Controller" >
- < form novalidate proper name = "f1" ng - submit = "SaveFile()" >
- < div way = "color: red" >{{ Message }}</ div >
- <table>
- <tr>
- <td> Select File : </ td >
- <td>
- < input type = "file" name = "file" accept = "paradigm/*" onchange = "angular.element(this).scope().selectFileforUpload(this.files)" required />
- < bridge class = "error" ng - show = "(f1.file.$dirty || IsFormSubmitted) && f1.file.$mistake.required" > Prototype required !</ span >
- < bridge class = "error" >{{ FileInvalidMessage }}</ span >
- </ td >
- </ tr >
- <tr>
- <td> Clarification : </ td >
- <td>
- < input type = "text" name = "uFileDescription" ng - model = "FileDescription" class = "{{(IsFormSubmitted?'ng-dirty' + (f1.uFileDescription.$invalid?' ng-invalid':''):'')}}" autofocus />
- </ td >
- </ tr >
- <tr>
- <td> </ td >
- <td>
- < input type = "submit" value = "Upload File" />
- </ td >
- </ tr >
- </ table >
- </ form >
- </ div >
- @department Scripts {
- < script src = "~/Scripts/AngularController/Part8Controller.js" ></ script >
- }
Pace-8: RUN APPLICATION.
amiesseciplaccont.blogspot.com
Source: http://shiva0shukla.blogspot.com/2015/05/how-to-upload-files-with-angularjs-and.html