0

Basically we would like to provide an option to users to upload their photo into SharePoint 2013 profile (on-premise). However, this upload happens from within SAP Portal.

What is the best option to enable upload functionality from non-SharePoint site (specifically SAP Portal in this case)? I tried to look at REST API but did not find enough examples which would also address cross-domain error.

Any pointers is highly appreciated. Thanks.

0

In SharePoint 2013, you can do with REST API to upload files.

Simple way is to open url of upload page of library in Iframe in your non-sharepoint site like sharepoint-server/_layouts/upload.aspx?List='listid'

I am assuming these files will upload to in some library. so in that case see the below code to upload files in library.

So here is another way. Below is the code for uploading file from app which is cross domain too. Check the code and modify it according to your need.

var appWebUrl = "";
var targetSiteUrl = "";
var digest = "";
var ready = false;

// extract the parameters from the page url (appweburl and hosturl
$(document).ready(function () {
    var params = document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
        var param = params[i].split("=");
        switch (param[0]) {
            case "SPAppWebUrl":
                appWebUrl = decodeURIComponent(param[1]);
                break;
            case "SPHostUrl":
                targetSiteUrl = decodeURIComponent(param[1]);
                break;
        }
    }

    // store the digest value for easy use later
    digest = $("#__REQUESTDIGEST").val();

    // load the request executor script, once ready set a flag that can be used to check against later
    $.getScript(appWebUrl + "/_layouts/15/SP.RequestExecutor.js", function () {
        ready = true;
    });
});


function UploadFile() {
    // if we have not finished loading scripts then display an alert
    if (!ready) {
        alert("Please wait for the page to finish loading before attempting to upload a file");
        return;
    }

    // get the file reference
    var docLibrary = 'Documents';
    var fileInput = $('#fileSelectorInput');

    // if we couldnt get a reference to the file input then alert the user and return
    if (!fileInput || fileInput.length != 1) {
        alert('An error occured processing your input.');
        return;
    }
    else if (!fileInput[0].files) {
        alert("It doesn't look like your browse supports uploading files in this way");
        return;
    }
    else if (fileInput[0].files.length <= 0) {
        alert("Please select a file and try again.");
        return;
    }

    // for each file in the list of files process the upload
    for (var i = 0; i < fileInput[0].files.length; i++) {
        var file = fileInput[0].files[i];
        ProcessUpload(file, docLibrary, '');
    }
}

function ProcessUpload(fileInput, docLibraryName, folderName) {
    var reader = new FileReader();
    reader.onload = function (result) {
        var fileName = '',
         libraryName = '',
         fileData = '';

        var byteArray = new Uint8Array(result.target.result)
        for (var i = 0; i < byteArray.byteLength; i++) {
            fileData += String.fromCharCode(byteArray[i])
        }

        // File will perform the actual upload
        PerformUpload(docLibraryName, fileInput.name, folderName, fileData);
    };
    reader.readAsArrayBuffer(fileInput);
}

function PerformUpload(libraryName, fileName, folderName, fileData) {
    var url;

    // if there is no folder name then just upload to the root folder
    if (folderName == "") {
        url = appWebUrl + "/_api/SP.AppContextSite(@TargetSite)/web/lists/getByTitle(@TargetLibrary)/RootFolder/Files/add(url=@TargetFileName,overwrite='true')?"

+ "@TargetSite='" + targetSiteUrl + "'" + "&@TargetLibrary='" + libraryName + "'" + "&@TargetFileName='" + fileName + "'"; } else { // if there is a folder name then upload into this folder url = appWebUrl + "/_api/SP.AppContextSite(@TargetSite)/web/lists/getByTitle(@TargetLibrary)/RootFolder/folders(@TargetFolderName)/files/add(url=@TargetFileName,overwrite='true')?" + "@TargetSite='" + targetSiteUrl + "'" + "&@TargetLibrary='" + libraryName + "'" + "&@TargetFolderName='" + folderName + "'" + "&@TargetFileName='" + fileName + "'"; }

    // use the request executor (cross domain library) to perform the upload
    var reqExecutor = new SP.RequestExecutor(appWebUrl);
    reqExecutor.executeAsync({
        url: url,
        method: "POST",
        headers: {
            "Accept": "application/json; odata=verbose", "X-RequestDigest": digest
        },
        contentType: "application/json;odata=verbose",
        binaryStringRequestBody: true,
        body: fileData,
        success: UploadSuccess,
        error: function (x, y, z) {
        }
    });
}

function UploadSuccess(x, y, z) {
    var file = JSON.parse(x.body);
    var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
    getItem.done(function (listItem, status, xhr) {
        var changeItem = updateListItem(listItem.d.__metadata);
        changeItem.done(function (data, status, xhr) {
        });
        changeItem.fail(onError);
    });
    getItem.fail(onError);
    alert("Success! Your file was uploaded to SharePoint.");
}

function getListItem(fileListItemUri) {
    debugger;
    fileListItemUri = fileListItemUri.replace(targetSiteUrl, '{0}');
    fileListItemUri = fileListItemUri.replace('_api/Web', '_api/sp.appcontextsite(@target)/web');
    var listItemAllFieldsEndpoint = String.format(fileListItemUri + "?@target='{1}'", appWebUrl, targetSiteUrl);
    return $.ajax({
        url: listItemAllFieldsEndpoint,
        type: "GET",
        headers: { "accept": "application/json;odata=verbose" }
    });
}

function updateListItem(itemMetadata) {
    var listItemUri = itemMetadata.uri.replace('_api/Web', '_api/sp.appcontextsite(@target)/web');
    var listItemEndpoint = String.format(listItemUri + "?@target='{0}'", targetSiteUrl);
    var body = String.format("{{'__metadata':{{'type':'{0}'}},'FileLeafRef':'{1}','Title':'{2}','Document_x0020_Type':'{3}'}}",
        itemMetadata.type, $('#fileNmInput').val(), $('#titleInput').val(), $('#doctypeInput').val());
    return $.ajax({
        url: listItemEndpoint,
        type: "POST",
        data: body,
        headers: {
            "X-RequestDigest": digest,
            "content-type": "application/json;odata=verbose",
            "content-length": body.length,
            "IF-MATCH": itemMetadata.etag,
            "X-HTTP-Method": "MERGE"
        }
    });
}

// Display error messages. 
function onError(error) {
    alert(error.responseText);
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.