Search This Blog

Tuesday, March 1, 2016

SharePoint 2013 working with file and folders: How to create new SharePoint folder using REST services

Till now we learned how to fetch folder information using SharePoint REST services. Now we will see how to create a new folder using SharePoint REST service.

Following is the SharePoint REST service:

"/_api/web/folders"

All you need to pass to this service is the Server Relative URL. You can create this using the folder's Server Relative URL in which you want to create folder plus new folder's name.

Following is the sample code:

<html>
<head>
<script src="/Site%20Assets/js/jquery-1.11.1.min.js"></script>
<script>

function AddFolder()
{
var digest = "";
var folderName = $("#txtFName").val();
$.ajax(
{
                url: "/_api/contextinfo",                                                                              
                method: "POST",
                headers: {
                                "ACCEPT": "application/json;odata=verbose",
                                "content-type": "application/json;odata=verbose"
                },
                success: function (data) {
                digest = data.d.GetContextWebInformation.FormDigestValue;
                },
                error: function (data) {
                                //alert("Error occured." + data);
                }
}).done(function() {
                $.ajax(
                {
                url: "/_api/web/folders",
                data: JSON.stringify({ '__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': '/testdoc/' + folderName}),
                method: "POST",
                headers: {
                                "ACCEPT": "application/json;odata=verbose",
                                "content-type": "application/json;odata=verbose",
                                "X-RequestDigest": digest
                },
                success: function (data) {
                                alert("Done successfully");
                },
                error: function (data) {
                                alert("Error occured." + data);
                }
});          
});                                          
}
</script> 
</head>
<body>
<div>
                <input type="text"  value="" id="txtFName"> </input>
</div> 
<div>
                <input type="submit" onclick="AddFolder()" value="Add Folder"> </input>
</div>
</body>
</html>


No comments:

Post a Comment