Tuesday 30 August 2016

Upload the document using REST API in the SharePoint 2013

Below scripts are used to upload the document using REST API in the SharePoint site.

$(document).ready(function () {
    SP.SOD.executeOrDelayUntilScriptLoaded(waitForCalloutScript, 'SP.js');
   
    $.getScript("/_layouts/15/" + "SP.RequestExecutor.js", function () {
        SP.RequestExecutorInternalSharedUtility.BinaryDecode = function SP_RequestExecutorInternalSharedUtility$BinaryDecode(data) {
            var ret = '';
            if (data) {
                var byteArray = new Uint8Array(data);
                for (var i = 0; i < data.byteLength; i++) {
                    ret = ret + String.fromCharCode(byteArray[i]);
                }
            }
            ;
            return ret;
        };
        SP.RequestExecutorUtility.IsDefined = function SP_RequestExecutorUtility$$1(data) {
            var nullValue = null;
            return data === nullValue || typeof data === 'undefined' || !data.length;
        };
        SP.RequestExecutor.ParseHeaders = function SP_RequestExecutor$ParseHeaders(headers) {
            if (SP.RequestExecutorUtility.IsDefined(headers)) {
                return null;
            }
            var result = {};
            var reSplit = new RegExp('\r?\n');
            var headerArray = headers.split(reSplit);
            for (var i = 0; i < headerArray.length; i++) {
                var currentHeader = headerArray[i];
                if (!SP.RequestExecutorUtility.IsDefined(currentHeader)) {
                    var splitPos = currentHeader.indexOf(':');
                    if (splitPos > 0) {
                        var key = currentHeader.substr(0, splitPos);
                        var value = currentHeader.substr(splitPos + 1);
                        key = SP.RequestExecutorNative.trim(key);
                        value = SP.RequestExecutorNative.trim(value);
                        result[key.toUpperCase()] = value;
                    }
                }
            }
            return result;
        };
        SP.RequestExecutor.internalProcessXMLHttpRequestOnreadystatechange = function SP_RequestExecutor$internalProcessXMLHttpRequestOnreadystatechange(xhr, requestInfo, timeoutId) {
            if (xhr.readyState === 4) {
                if (timeoutId) {
                    window.clearTimeout(timeoutId);
                }
                xhr.onreadystatechange = SP.RequestExecutorNative.emptyCallback;
                var responseInfo = new SP.ResponseInfo();
                responseInfo.state = requestInfo.state;
                responseInfo.responseAvailable = true;
                if (requestInfo.binaryStringResponseBody) {
                    responseInfo.body = SP.RequestExecutorInternalSharedUtility.BinaryDecode(xhr.response);
                }
                else {
                    responseInfo.body = xhr.responseText;
                }
                responseInfo.statusCode = xhr.status;
                responseInfo.statusText = xhr.statusText;
                responseInfo.contentType = xhr.getResponseHeader('content-type');
                responseInfo.allResponseHeaders = xhr.getAllResponseHeaders();
                responseInfo.headers = SP.RequestExecutor.ParseHeaders(responseInfo.allResponseHeaders);
                if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 1223) {
                    if (requestInfo.success) {
                        requestInfo.success(responseInfo);
                    }
                }
                else {
                    var error = SP.RequestExecutorErrors.httpError;
                    var statusText = xhr.statusText;
                    if (requestInfo.error) {
                        requestInfo.error(responseInfo, error, statusText);
                    }
                }
            }
        };
    });  
   
});

// SET THESE INITIAL PARAMETERS
// Name of the category list
var _categoryListTitle = "Template Categories";
// Name of the document Template Library
var _docTemplateListTitle = "New Document Templates"
// Name of the target document library
var _destinationLibTitle = "Project Documents";
var _destinationLibRootFolder = "ProjectDocuments";
// URL of the target document library, set after SP.js is loaded
var _destinationlibUrl = "";
var _destinationlibUrlNew = "";
// document properties file name
var _documentPropertiesFileName = "documentProps.aspx";
var _resultHTML = '';
var _tabHTML = '';
var _ctx;
var _sourceFile;
var _destinationFileUrl;
var _destinationFile;
var _newId
var collListItem;
function waitForCalloutScript() {
 _destinationlibId = window.frameElement.dialogArgs;
 _siteServerRelativeUrl = _spPageContextInfo.siteServerRelativeUrl;
 if (_siteServerRelativeUrl === "/")
  _siteServerRelativeUrl = "";
 //_destinationlibUrl = _siteServerRelativeUrl + "/ProjectDocuments/";
    SP.SOD.executeOrDelayUntilScriptLoaded(BuildTemplateSelectionPanel, 'callout.js');
}
// Build the Document Template tabs
function BuildTemplateSelectionPanel() {
    _ctx = new SP.ClientContext.get_current();
    if (_ctx != undefined && _ctx != null) {
        var _categoryList = _ctx.get_web().get_lists().getByTitle(_categoryListTitle);
  var _sourceList = _ctx.get_web().get_lists().getById(_destinationlibId);
  var _camlQuery = new SP.CamlQuery();
        var _categories = _categoryList.getItems(_camlQuery);
        _ctx.load(_categories);
  _ctx.load(_sourceList, 'Title', 'DefaultViewUrl');
  _ctx.executeQueryAsync(
            function (sender, args) {
    //var _sourceTitle = _sourceList.get_title();
    _destinationlibUrl = ShortenDefaultViewUrl(_sourceList.get_defaultViewUrl());
                _resultHTML += "<div id='tabCategories'><ul>";
                var _categoriesEnumerator = _categories.getEnumerator();
                while (_categoriesEnumerator.moveNext()) {
                    var _categoryItem = _categoriesEnumerator.get_current();
                    _resultHTML += "<li><a href='#" + _categoryItem.get_item('Title').replace(/\s+/g, '') + "'>" + _categoryItem.get_item('Title') + "</a></li>";
                    _tabHTML += "<div catid='" + _categoryItem.get_id() + "' id='" + _categoryItem.get_item('Title').replace(/\s+/g, '') + "'></div>"
                }
                _resultHTML += "</ul>" + _tabHTML + "</div>";
                $('#resultsdiv').empty();
                $('#resultsdiv').append(_resultHTML);
            },
            function (sender, args) {
                alert('Error occured: ' + args.get_message());
            });
        BuildTabs();
    }
}
function ShortenDefaultViewUrl(defaultViewUrl)
{
 var idx = defaultViewUrl.indexOf("/Forms", 1);
 return defaultViewUrl.slice(0,idx + 1);
}
function BuildTabs() {
    var _docTemplateList = _ctx.get_web().get_lists().getByTitle(_docTemplateListTitle);
    var _docTemplateByCategory = new SP.CamlQuery();
    var _docTemplates = _docTemplateList.getItems(_docTemplateByCategory);
    _ctx.load(_docTemplates, 'Include(FileLeafRef, Id,Category,Description0,DocIcon )');
    _ctx.executeQueryAsync(
        function (sender, args) {
            var _docTemplatesEnumerator = _docTemplates.getEnumerator();
            var calloutOptions;
            while (_docTemplatesEnumerator.moveNext()) {
                var _docTemplatesItem = _docTemplatesEnumerator.get_current();
                var _docImageUrl = "/_layouts/15/images/ic" + _docTemplatesItem.get_item('DocIcon') + ".png";
                var _elementId = "docTemp" + _docTemplatesItem.get_id();
                $("div[catid='" + _docTemplatesItem.get_item('Category').get_lookupId() + "']").append("<div id='" + _elementId + "' class='tab-content' style='padding:5px' ><a id='a" + _elementId + "' style='cursor:pointer' onclick=\"selectTemplate('" + _elementId + "','" + _docTemplatesItem.get_id() + "','" + _docTemplatesItem.get_item('DocIcon') + "');\"><img width='16' height='16' title='" + _docTemplatesItem.get_item('FileLeafRef') + "'" +
                            "+alt='" + _docTemplatesItem.get_item('FileLeafRef') + "' src='" + _docImageUrl + "' border='0'/>" + "&nbsp;" + _docTemplatesItem.get_item('FileLeafRef') + "</a></div>")
                calloutOptions = new CalloutOptions();
                calloutOptions.ID = _elementId + 'notificationcallout';
                calloutOptions.launchPoint = document.getElementById('a'+_elementId);
                calloutOptions.beakOrientation = 'topBottom';
                calloutOptions.content = _docTemplatesItem.get_item('Description0');
                calloutOptions.title = _docTemplatesItem.get_item('FileLeafRef');
                var callout = CalloutManager.createNew(calloutOptions);
                callout.set({ openOptions: { event: "hover" } });
                            
            }
            $("#tabCategories").tabs();
        },
         function (sender, args) {
             alert('Error occured: ' + args.get_message());
         });
}
// event for selecting the document template
function selectTemplate(elementid, id, docType) {
    $(".tab-content").css('background-color', 'white');
    $("#" + elementid).css('background-color', 'aqua');
    $("#selectedTemplate").val(id + "-" + docType);
}
// event for creating the document based on template
function CreateDocument() {
    if ((document.getElementById("txtFileName").value).length == 0) {
        alert("FileName should not be empty");
    }
    else if ((document.getElementById("selectedTemplate").value).length == 0) {
        alert("Please select a template for the new file");
    }
    else {
        _ctx = new SP.ClientContext.get_current();
        if (_ctx != undefined && _ctx != null) {
            // Get the Web site that is associated with the client context.
            this.web = _ctx.get_web();
            _ctx.load(this.web);
            // Returns the current list.
            this.sourceList = this.web.get_lists().getByTitle(_docTemplateListTitle);
            _ctx.load(this.sourceList);
            var _currentID = $("#selectedTemplate").val().split("-")[0];
            this.currentItem = sourceList.getItemById(_currentID);
            _ctx.load(this.currentItem);
            // Get the file that is represented by the item from a document library.
            _sourceFile = this.currentItem.get_file();
            _ctx.load(_sourceFile);
            _ctx.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),
                                   Function.createDelegate(this, this.onQueryFailed));
        }
    }
}
function onQuerySucceeded(sender, args) {
    if (_sourceFile != null) {
   
     var _fileName = document.getElementById("txtFileName").value + "." + $("#selectedTemplate").val().split("-")[1];
   
     //Get source file url
     var _sourceFileUrl = _sourceFile.get_serverRelativeUrl();
     var targetExecutor = new SP.RequestExecutor(_spPageContextInfo.webAbsoluteUrl);    
               
     $.ajax({
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/contextinfo",
                type: "POST",
                headers: {
                    "Accept": "application/json;odata=verbose"
                },
                success: function (data) {
                    var digest = data.d.GetContextWebInformation.FormDigestValue;
                    // Build executor action to retrieve the file data.
                    var getFileAction = {
                        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFileByServerRelativeUrl('" + _sourceFileUrl + "')/$value",
                        method: "GET",
                        binaryStringResponseBody: true,
                        success: function (getFileData) {
                            var notifyId = SP.UI.Notify.addNotification('Copying file... ' + _sourceFile.get_serverRelativeUrl() + ' to ' + _destinationLibTitle, true);
                            // Get the binary data.
                            //var result = data.body;
                            // Build executor action to copy the file data to the new location.
                            var copyFileAction = {
                                url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/getfolderbyserverrelativeurl('"+ _destinationLibRootFolder +"')/Files/Add(url='" + _fileName + "', overwrite=true)",
                                method: "POST",
                                headers: {
                                    "Accept": "application/json; odata=verbose",
                                    "X-RequestDigest": digest
                                },
                                contentType: "application/json;odata=verbose",
                                binaryStringRequestBody: true,
                                body: getFileData.body,
                                success: function (copyFileData) {
                                 SP.UI.Notify.removeNotification(notifyId);
                     SP.UI.Notify.addNotification('File copied successfully', false);                               
                                    var camlQuery = new SP.CamlQuery();
                                    camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>" + _fileName + "</Value></Eq></Where></Query><RowLimit>1</RowLimit></View>");
                                    var destinationContext = new SP.ClientContext(_spPageContextInfo.webAbsoluteUrl);
                                    var destiantionWeb = destinationContext.get_web();                                  
                                    var projDocumentsList = destiantionWeb.get_lists().getByTitle(_destinationLibTitle);
                                    var collListItem = projDocumentsList.getItems(camlQuery);
                                    destinationContext.load(collListItem);
                                    destinationContext.executeQueryAsync(
                                        function (sender, args) {
                                            var listItemId = '';
                                            var listItemEnumerator = collListItem.getEnumerator();
                                            while (listItemEnumerator.moveNext()) {
                                                var oListItem = listItemEnumerator.get_current();
                                                listItemId = oListItem.get_id();
                                            }
                                            window.location = _spPageContextInfo.webAbsoluteUrl + "/"+ _destinationLibRootFolder +"/" + "Forms/" + _documentPropertiesFileName + "?ID=" + listItemId + "&docurl=" + _spPageContextInfo.webServerRelativeUrl + "/"+ _destinationLibRootFolder +"/"+_fileName;
                                        },
                                        function (sender, args) {
                                            alert('Error occured: ' + args.get_message());
                                        });                                  
                                },
                                error: function (ex) {
                                    //show your 'failed' message
                                     SP.UI.Notify.addNotification('Error copying file', false);
                      SP.UI.Notify.removeNotification(notifyId);
                                     alert(ex);
                                }
                            };
                            targetExecutor.executeAsync(copyFileAction);
                        },
                        error: function (ex) {
                            //fail                           
                            alert(ex);
                        }
                    };
                    targetExecutor.executeAsync(getFileAction);
                },
                error: function (ex) {
                    //fail
        alert(ex);
                }
            });           
    }
}
// Delegate that is called when server operation is completed with errors.
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

No comments:

Post a Comment