Environment: Using jQuery, REST, SharePoint 2013 Enterprise,
knockout JS
Requirement: Create a folder in a document library with
current year as the folder name using REST. Check if folder exists already, else create a
new folder.
Prerequisite: knockout and latest jQuery must be defined.
Code:
var currentYear = ko.observable();
var documentLibraryName = “DocumentLibraryName”;
var serverUrl = “http://webServerURL”;
var documentLibraryName = “DocumentLibraryName”;
var serverUrl = “http://webServerURL”;
//Following code should be executed on page load
self.currentYear = ko.computed(function () {
self.currentYear = ko.computed(function () {
currentYear = (new
Date).getFullYear();
return (new
Date).getFullYear();
});
//fileUpload method is used to upload a file to a folder in SharePoint
document library
self.fileUpload = function () {
self.doesFolderExist();
….
….
…
};
//doesFolderExist method is used to check if the folder already exists
in the document library and create a new folder if does not exist.
self.doesFolderExist = function (){
self.doesFolderExist = function (){
var
fileCollectionEndpoint = serverUrl +
"/_api/web/getfolderbyserverrelativeurl('" + documentLibraryName +"/"+currentYear+
"')";
return $.ajax({
url:
fileCollectionEndpoint,
type:
"GET",
headers: {
"accept":
"application/json;odata=verbose",
"X-RequestDigest":
window.top.$("#__REQUESTDIGEST").val()
},
success:
function (data) {
alert("Folder
already exists");
},
error: function (data) {
//Folder
does not exist, so create a new folder
self.createFolder();
}
});
};
//Create a folder in document library
self.createFolder = function ()
self.createFolder = function ()
{
var
fileCollectionEndpoint = serverUrl +
"/_api/web/getfolderbyserverrelativeurl('" + documentLibraryName +
"')/folders/add(url=\'" + currentYear + "\')";
return $.ajax({
url:
fileCollectionEndpoint,
type:
"POST",
headers:
{
"X-RequestDigest": window.top.$("#__REQUESTDIGEST").val(),
"accept":
"application/json;odata=verbose",
"content-type":
"application/json;odata=verbose"
},
success:
function (data) {
//alert(‘Folder
created successfully’);
},
error: function (jqXHR, textStatus, errorThrown)
{
//handle
error...
alert('Failed
to create folder in library.');
}
});
};
References:
No comments:
Post a Comment