SharePoint Pals
 | Sign In
How to upload files from Asp.Net MVC application to SharePoint 2013 with Angualr Js
by Sriram Varadarajan 21 Apr 2015
Author
Enterprise Architect
Visits   
Today  :   7     Total  :    9481

I had an opportunity to work on an assignment related to upload of documents from Asp.Net MVC application into a SharePoint site with Angular Js.   Follow the the simple steps provided below to upload documents into SharePoint 2013 document library with Angular Js

Create a ASP.NET MVC Application and install jquery and Angular JS from Nuget.

Modify the Index.Cshtml(under View->Home) with the following code

 <table style="width:100%;">
     <tr>
         <td>
             <label for="lblinput">Input the search string</label>
         </td>
         <td>
             <input id="Text1″ type="text" ng-model="Search" value="Category" />
         </td>
     </tr>
     <tr>
         <td>
             <input id="Submit1″ type="submit" value="submit" ng-click="GetDetails()" />
         </td>
     </tr>
 </table>
 <table style="width:100%;">
     <tr>
         <td>
             <label for="lblinput">Add value to Sharepoint</label>
         </td>
         <td>
             <input id="Text1″ type="text" ng-model="NewItem" value="Category" />
         </td>
     </tr>
     <tr>
         <td>
             <input id="Submit1″ type="submit" value="submit" ng-click="Add()" />
         </td>
     </tr>
 </table>
 <table>
     <tr>
         Select File to Upload :
         <input id="inputFile" type="file" />
         <input type="button" ng-click="Upload();" value="Upload" />
     </tr>
 </table>
 <h1>{{title}}</h1> 
 {{station_list}}

Create a Script.js File and copy and paste the below code:

 var app = angular.module("myApp", []);
 //This is to get the data from sharepoint
 app.controller("myController", function($scope, $http, $q) {
             $scope.GetDetails = function() {
                     $http({
                             withCredentials: true,
                             method: 'GET',
                             headers: {"Accept": "application/json;odata = verbose"
                             },
                             url: "http://[SharePoint Site]/_api/lists/getbytitle('" + $scope.Search + "')/items"
                         })
                         .then(function(response) {
                             var station_list = [];
                             $.each(response.data.d.results, function(key, value) {
                                 station_list.push(value.Title);
                             });
                             $scope.station_list = station_list;
                             $scope.title = "Data From Sharepoint";
                         });
                 };
                 //To get the formdigestvalue, which is required to insert data to sharepoint
                 //Define the service call
             function getFormDigest() {
                 //Fetch the Url
                 // JSRequest.EnsureSetup();
                 // var appweburl = decodeURIComponent(JSRequest.QueryString['SPAppWebUrl']);
                 var dfd = $q.defer();
                 //Http post to the context info rest service
                 $http.post("http://[SharePoint Site]/_api/contextinfo&#8221;, {
                     data: ",
                     headers: {"Accept": "application/json;odata = verbose",
                         "Content-Type": "text/xml"
                     },
                 }).success(function(data) {
                 //Resolve the FormDigestValue from the success callback.
                 dfd.resolve(data.d.GetContextWebInformation.FormDigestValue);
                 // alert(data.d.GetContextWebInformation.FormDigestValue);
             }).error(function() {
                 dfd.reject("error finding form digest");
             });
             return dfd.promise;
         }
         //Inserting data to sharepointt
         $scope.Add = function() {
             alert($scope.NewItem);
             $http.defaults.headers.common.Accept = "application/json;odata = verbose";
             $http.defaults.headers.post['Content-Type'] = 'application/json;odata = verbose';
             $http.defaults.headers.post['X-Requested-With'] = 'XMLHttpRequest';
             $http.defaults.headers.post['If-Match'] = "*";
             $http.defaults.headers.post['X-HTTP-Method'] = "";
             getFormDigest().then(function(digest) {
                 $http.defaults.headers.post['X-RequestDigest'] = digest;
                 var dfd = $q.defer();
                 $http.defaults.headers.post['X-HTTP-Method'] = "";
                 // To create a item in list, use the below URL
                 var restUrl = "https: //[SharePoint Site]/_api/lists/getbytitle('Testing&#8217;)/items";
                     // To attach a file to lib use the below REST URL
                     //url: "http://[SharePoint Site]/_api/web/lists/GetByTitle('Testing&#8217;)/RootFolder/Files/Add(url='" + file.name + "', overwrite=true)",
                     // file attached for list item — item id is required for attachment.
                     //url: "http://[SharePoint Site]/_api/web/lists/GetByTitle('&#8221; + listName + "')/items(" + id + ")/AttachmentFiles/add(FileName='" + file.name + "')",
                     // if (document.getElementById("inputFile").files.length === 0) {
                     // alert("Select a file!");
                     //return;
                     //}
                     //var restUrl = "http://[SharePoint Site]/_api/web/lists/GetByTitle('Testing&#8217;)/items(4)/AttachmentFiles/add(FileName='" + file.name + "')";
                     $http.post(restUrl, {
                         __metadata: {type: 'SP.Data.TestingListItem'},
                         Title: $scope.NewItem
                             // binaryStringRequestBody: true,
                             // body: binary
                     }).success(function(data) {
                         //resolve the new data
                         //console.log("success");
                         // if (document.getElementById("inputFile").files.length === 0) {
                         // alert("Select a file!");
                         //return;
                         //}
                         //Upload file to list/documentlibrary provided the file is been selected
                         if (document.getElementById("inputFile").files.length > 0) {
                             var parts = document.getElementById("inputFile").value.split("\\");
                             var filename = parts[parts.length– 1];
                             var file = document.getElementById("inputFile").files[0];
                             var binary = ";
                             var restUrlatt = "http://[SharePoint Site]/_api/web/lists/GetByTitle('Testing')/items(" + data.d.ID + ")/AttachmentFiles/add(FileName='" + file.name + "')";
                                 getFileBuffer(file).then(
                                     function(buffer) {
                                         var bytes = new Uint8Array(buffer);
                                         alert(bytes.length);
                                         for (var b = 0; b < bytes.length; b++) {
                                             binary += String.fromCharCode(bytes[b]);
                                         }
                                         $http.post(restUrlatt, {
                                             __metadata: {
                                                 type: "SP.Data.TestingListItem"
                                             },
                                             binaryStringRequestBody: true,
                                             body: binary
                                         }).success(function(data) {
                                             //resolve the new data
                                             console.log("success");
                                             dfd.resolve(data.d);
                                         }).error(function(data) {
                                             dfd.reject("failed to add book");
                                             console.log("error");
                                         });
                                         return dfd.promise;
                                     });
                         }
                         dfd.resolve(data.d);
                     }).error(function(data) {
                         dfd.reject("failed to add book");
                         console.log("error");
                     });
                 return dfd.promise;
             })
         };
blog comments powered by Disqus

SharePoint Pals

Pals
SharePoint Pals, a community portal for SharePoint developers, Administrators and End Users. Let's join hands and share the point together.
Read this on mobile

Training

Angular Js Training In Chennai
Advanced Angular Js training with real world developer scenarios
Angular Js, Web Api and Ionic for .Net Developers
All in one client side application development for .Net developers
Angular Js For SharePoint Developers
Get ready for the future. Its no more just C#

Get Connected

SharePoint Resources

SharePoint 2013 and 2010 Web Parts
Free Web Parts with Source Code for SharePoint Community




SharePoint 2013 Books and Tutorials
Collection of free SharePoint 2013 books and tutorials (eBooks, pdfs)

Supported By

Contribute your article and be eligible for a one month Free Subscription for Plural Sight. The Author of the most popular New Article (published in the previous month) will be awarded with a Free One month Plural Sight Subscription. Article can be sent to articles@sharepointpals.com in a word document.

Related Resources

Recent Tweets

Twitter January 15, 00:25
How To Enable Target Value And Actual Value In #D3 Gauge Chart https://t.co/VxSi4QnNrC

Twitter January 15, 00:24
How To Open #SharePoint List Hyperlink Column In Modal #Popup Window https://t.co/EQ7HkoZDkX

Twitter January 15, 00:24
Quick Introduction To #Asp.NetCore And It’s Features https://t.co/zAXObHCFpH

Twitter January 15, 00:22
How To Configure #PerformancePoint Services To Use Secure Store In #SharePoint 2013 https://t.co/LEwnUoI7EY

Twitter January 15, 00:21
How To Block Or Disable #Office365 Services https://t.co/Yvp2VPFIRP

Follow us @SharePointPals
Note: For Customization and Configuration, CheckOutRecent Tweets Documentation