How to upload files from Asp.Net MVC application to SharePoint 2013 with Angualr Js

Sriram Varadarajan
 
Solution Architect
April 21, 2015
 
Rate this article
 
Views
15722

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”, {
                     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’)/items";
                     // To attach a file to lib use the below REST URL
                     //url: "http://[SharePoint Site]/_api/web/lists/GetByTitle('Testing’)/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('” + 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’)/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;
             })
         };
Category : Angular, SharePoint

Author Info

Sriram Varadarajan
 
Solution Architect
 
Rate this article
 
Sriram is a Technology Evangelist with 15+ years experience in Microsoft Technologies. He is an enterprise architect working for large pharmaceutical organization which has presence globally with largest Microsoft implementation ...read more
 

Leave a comment