다음을 통해 공유


SharePoint Hosted Apps - Create Enterprise WIKI page using REST API

Introduction

This article describes how to use the List Template model to create enterprise wiki pages using REST API.  Thanks to Steve Curran for helping out.  As you might notice, the question on MSDN forum talks about using JSOM which is also an option.

Scenario

*We need to create a knowledge base article based on support tickets.
*
Enterprise Wiki is only supported in a site collection once it has the publishing feature enabled.  To enable this feature, go to top level site. From Site Settings, to Site collection features and activate "SharePoint Server Publishing Infrastructure".  Then, activate "SharePoint Server Publishing" from Site Settings, Manage site features.

Hint:  You can add a page in the browser based on Enterprise Wiki template, make all necessary text formatting changes, and save.  Then simply download the page from the Pages library, open with your favorite editor (notepad), and extract the necessary details to add to your template.

WikiModel = {
 
    listname: 'Pages',
    wikiUrl: 'http://www.mysite.com/sitecollection/wiki',
    wikiSearch: '/_layouts/15/osssearchresults.aspx?u=http://www.mysite.com/sitecollection/wiki&k=',
    serverRelativeUrl: '/sitecollection/wiki/Pages/Support', //this is using Support sub folder within Pages library;
    wikiCatalog: 'http://www.mysite.com/sitecollection/_catalogs/masterpage/EnterpriseWiki.aspx',
    wikiTemplate: '',
    templateBody: '',
    wikiBody: '',
    editUrl: 'socialcomm/createwiki.aspx',
    selectonly: '&$select=Id',
    typeofdata: 'SP.Data.PagesItem',
    callbackhandler: undefined,
 
    init: function  (cbhandler) {
        WikiModel.callbackhandler = cbhandler;
 
        WikiModel.wikiTemplate = '<%@ Page Inherits="Microsoft.SharePoint.Publishing.TemplateRedirectionPage,Microsoft.SharePoint.Publishing,Version=15.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c" %> <%@ Reference VirtualPath="~TemplatePageUrl" %> <%@ Reference VirtualPath="~masterurl/custom.master" %><%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>' +
            '<html xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"><head>' +
            '<!--[if gte mso 9]><SharePoint:CTFieldRefs runat=server Prefix="mso:" FieldList="FileLeafRef,Comments,PublishingStartDate,PublishingExpirationDate,PublishingContactEmail,PublishingContactName,PublishingContactPicture,PublishingPageLayout,PublishingVariationGroupID,PublishingVariationRelationshipLinkFieldID,PublishingRollupImage,Audience,PublishingIsFurlPage,SeoBrowserTitle,SeoMetaDescription,SeoKeywords,RobotsNoIndex,PublishingPageContent,AverageRating,RatingCount,Ratings,e1a5b98cdd71426dacb6e478c7a5882f,TaxCatchAllLabel"><xml>' +
            '<mso:CustomDocumentProperties>' +
            '<mso:PublishingContact msdt:dt="string"></mso:PublishingContact>' +
            '<mso:PublishingIsFurlPage msdt:dt="string">1</mso:PublishingIsFurlPage>' +
            '<mso:display_urn_x003a_schemas-microsoft-com_x003a_office_x003a_office_x0023_PublishingContact msdt:dt="string"></mso:display_urn_x003a_schemas-microsoft-com_x003a_office_x003a_office_x0023_PublishingContact>' +
            '<mso:PublishingContactPicture msdt:dt="string"></mso:PublishingContactPicture>' +
            '<mso:RobotsNoIndex msdt:dt="string">0</mso:RobotsNoIndex>' +
            '<mso:PublishingContactName msdt:dt="string"></mso:PublishingContactName>' +
            '<mso:PublishingPageLayoutName msdt:dt="string">EnterpriseWiki.aspx</mso:PublishingPageLayoutName>' +
            '<mso:Comments msdt:dt="string"></mso:Comments>' +
            '<mso:PublishingContactEmail msdt:dt="string"></mso:PublishingContactEmail>' +
            '<mso:PublishingPageLayout msdt:dt="string">' + WikiModel.wikiCatalog + ', Basic Page</mso:PublishingPageLayout>' +
            '<mso:TaskStatus msdt:dt="string">Not Started</mso:TaskStatus>' +
            '<mso:PublishingPageContent msdt:dt="string"></mso:PublishingPageContent>' +
            '<mso:e1a5b98cdd71426dacb6e478c7a5882f msdt:dt="string"></mso:e1a5b98cdd71426dacb6e478c7a5882f>' +
            '<mso:Wiki_x0020_Page_x0020_Categories msdt:dt="string"></mso:Wiki_x0020_Page_x0020_Categories>' +
            '<mso:PublishingRollupImage msdt:dt="string"></mso:PublishingRollupImage>' +
            '<mso:Audience msdt:dt="string"></mso:Audience>' +
            '<mso:TaxCatchAll msdt:dt="string"></mso:TaxCatchAll>' +
            '</mso:CustomDocumentProperties>' +
            '</xml></SharePoint:CTFieldRefs><![endif]-->' +
            '<title>[[>Title]]</head>';
 
        WikiModel.templateBody = '<p>​​​​​​​​This wiki article is generated based on existing issue. For further details, contact Support at ' +
            '<a href="mailto:support@mysite.com">support@mysite.com​​</a>.<br/></p>' +
            '<h2>Reported ​​​​I​ssue​</h2>' +
            '<p>​​​[[>Reported Issue]]<br/></p>' +
            '<p><br/></p>' +
            '<h2>​​Resolution<br/></h2>' +
            '<p>[[>Resolution]]<br/></p>';
    },
 
    additem: function  (dialogResult, returnValue) {
        if (dialogResult == SP.UI.DialogResult.OK) {
            var pageName = "Support - X" + Date.now();
 
            WikiModel.wikiTemplate = WikiModel.wikiTemplate.replace('[[>Title]]', 'Support');
            WikiModel.wikiBody = WikiModel.templateBody;
 
            WikiModel.wikiBody = WikiModel.wikiBody.replace('[[>Reported Issue]]', returnValue.reported);
            WikiModel.wikiBody = WikiModel.wikiBody.replace('[[>Resolution​]]', returnValue.external);
 
            var arrHTML = [WikiModel.wikiTemplate];
            var myblob = new Blob(arrHTML, { type: 'text/plain' });            
 
            WikiModel.url = appweburl + svc_apiurl + svc_local_sitecollurl + "GetFolderByServerRelativeUrl('"  + WikiModel.serverRelativeUrl + "')/Files" +
                                "/Add(url='" + pageName + ".aspx', overwrite=true)?@target='" + WikiModel.wikiUrl + "'";
 
            WikiModel.getFileBuffer(myblob)
                .fail(WikiModel.errorHandler).then(WikiModel.createorupdateitem)
                .fail(WikiModel.errorHandler).then(WikiModel.getbyServerPath)
                .fail(WikiModel.errorHandler).then(WikiModel.updateProperties);
        }
    },
 
    createorupdateitem: function  (arrayBuffer) {
        var deferred = $.Deferred();
 
        var requestHeaders = {
            "Accept": "application/json; odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        }
 
        var executor = new SP.RequestExecutor(appweburl);
        executor.executeAsync(
            {
                url: WikiModel.url,
                contentType: "application/json;odata=verbose",
                method: "POST",
                body: arrayBuffer,
                binaryStringRequestBody: true,
                headers: requestHeaders,
                success: function  (data) {
                    var jsonObject = JSON.parse(data.body);
 
                    deferred.resolve(jsonObject.d.ServerRelativeUrl);
                },
                error: function  (data, errorCode, errorMessage) {
                    deferred.reject('unable to create new wiki page -- ' + errorCode + ' -- ' + errorMessage);
                }
            }
        );
 
        return deferred.promise();
    },
 
    getFileBuffer: function  (file) {
        var deferred = $.Deferred();
        var reader = new FileReader();
        reader.onload = function  (e) {
            var fileData = '';
            var byteArray = new Uint8Array(e.target.result);
            for (var i = 0; i < byteArray.byteLength; i++) {
                fileData += String.fromCharCode(byteArray[i])
            }
 
            deferred.resolve(fileData);
        }
        reader.onerror = function  (e) {
            deferred.reject(e.target.error);
        }
 
        reader.readAsArrayBuffer(file);
        return deferred.promise();
    },
 
    getbyServerPath: function  (fileUrl) {
        WikiModel.url = appweburl + svc_apiurl + svc_local_sitecollurl + "GetFileByServerRelativeUrl('"  + fileUrl + "')/ListItemAllFields?@target='" + WikiModel.wikiUrl + "'" + WikiModel.selectonly;
 
        var deferred = $.Deferred();        
        var executor = new SP.RequestExecutor(appweburl);
 
        executor.executeAsync(
            {
                url: WikiModel.url,
                method: "GET",
                headers: { "Accept":  "application/json; odata=verbose"  },
                success: function  (data) {
                    var jsonObject = JSON.parse(data.body);
 
                    deferred.resolve(jsonObject.d.Id);
                },
                error: function  (data, errorCode, errorMessage) {
                    deferred.reject('unable to fetch new wiki page -- ' + errorCode + ' -- ' + errorMessage);
                }
            }
        );
 
        return deferred.promise();
    },
 
    updateProperties: function  (fileId) {
        WikiModel.url = appweburl + svc_apiurl + svc_local_sitecollurl + "lists/getByTitle('"  + WikiModel.listname + "')/items("  + fileId + ")?@target='"  + WikiModel.wikiUrl + "'";
 
        var setdata = {
            __metadata: { "type": WikiModel.typeofdata },
            PublishingPageContent: WikiModel.wikiBody
        };
 
        var requestHeaders = {
            "content-type": "application/json;odata=verbose",
            "Accept": "application/json; odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "X-HTTP-Method": "MERGE",
            "If-Match": "*"
        }
 
        var executor = new SP.RequestExecutor(appweburl);
        executor.executeAsync(
            {
                url: WikiModel.url,
                contentType: "application/json;odata=verbose",
                method: "POST",
                body: JSON.stringify(setdata),
                headers: requestHeaders,
                success: WikiModel.onSuccess,
                error: function  (error) {
                    WikiModel.errorHandler(JSON.stringify(error));
                }
            }
        );
    },
 
    onSuccess: function  (data) {
        alert('Wiki article created');
 
        WikiModel.callbackhandler();
    },
 
    errorHandler: function  (data) {
        alert(data);
    },
 
    displayaddform: function  (pDataToEdit) {
        var args1 = {
            command: 'add',
            editdata: pDataToEdit
        };
 
        var options = {
            url: WikiModel.editUrl,
            showClose: true,
            title: 'Edit Wiki Article',
            dialogReturnValueCallback: WikiModel.additem,
            args: args1
        };
 
        SP.UI.ModalDialog.showModalDialog(options);
    }
};

References

SharePoint 2013:  Use a List Template Model with REST API