Madhanmohan Devarajan

Madhanmohan Devarajan

  • 231
  • 8.2k
  • 1.7m

How to upload PDF to SharePoint library using AngularJS

Dec 1 2016 12:22 PM

I am trying to upload PDF document created dynamically using angularJS and PDFmake(js library) to SharePoint library using REST API, but the PDF document uploaded to the document library has 0KB and when i tried to open it shows error "Failed to open".

While using var doc = pdfMake.createPdf(docDefinition).download(); it works, but when i tried to upload "baseService.fileUploadRequest(doc.getBuffer(), url);" using this it uploads the empty pdf file to SharePoint.

Flow : HTML button click -> Controller -> Service -> BaseSvc

Controller:

$scope.uploadPdf = function ($location) {

var employees = $scope.people;

var empList = [];

angular.forEach(employees, function(value, key) {

empList.push({Firstname: value.FirstName, Lastname: value.LastName, Address: value.Address});

});

var items = empList.map(function(item) {

return [item.Firstname, item.Lastname, item.Address];

});

var docDefinition = {

pageOrientation: 'landscape',

content: [

{ text: 'Employees List'},

{

style: 'styleTable',

table:

{

body:

[

[{ text: 'Firstname', style: 'header' },

{ text: 'Lastname' , style: 'header' },

{ text: 'Address' , style: 'header' },

],

].concat(items)

}

}

],

styles: {

header: {

bold: true,

color: '#000',

fontSize: 11

},

styleTable: {

color: '#666',

fontSize: 10

}

}

};

var doc = pdfMake.createPdf(docDefinition);

peopleService.fileUpload(doc)

.then(function (response) {

console.log(response);

$location.path("/");

});

};

}]);

})();

Service:

"use strict";

(function(){

angular.module("peopleApp")

.factory("peopleService",["baseSvc",function(baseService){

var listEndPoint = '/_api/web/lists';

var fileUpload = function(doc){

var url = "/_api/web/lists/GetByTitle('Documents')/RootFolder/Files/add(url='EmployeesDetails.pdf', overwrite=true)";

return baseService.fileUploadRequest(doc.getBuffer(), url);

};

return{

fileUpload:fileUpload

};

}]);

})();

BaseSvc:

"use strict";

(function () {

angular.module("peopleApp")

.factory("baseSvc", ["$http", "$q", function ($http, $q) {

var baseUrl = _spPageContextInfo.webAbsoluteUrl;

var fileUploadRequest = function(databuffer, url) {

var deferred = $q.defer();

$http({

url: baseUrl + url,

method: "POST",

processData: false,

data: databuffer,

transformRequest: angular.identity,

headers: {

"accept": "application/json;odata=verbose",

"X-RequestDigest": document.getElementById("__REQUESTDIGEST").value,

"Content-Type": undefined,

"content-length": databuffer.byteLength

}

}).success(function(result) {

deferred.resolve(result);

}).error(function(result, status) {

deferred.reject({

error: result,

status: status

});

});

return deferred.promise;

};

return {

fileUploadRequest: fileUploadRequest

};

}]);

})();


Answers (2)