0

i am getting error like the the site cannot be accessed in share point hosted app. it is occured when i moving the from one page to another page in the same app. please help me in advance

it is Default.aspx code

  <script>

      'use strict';

var appWebUrl, hostWebUrl;

jQuery(document).ready(function () {

    // Check for FileReader API (HTML5) support.
    if (!window.FileReader) {
        alert('This browser does not support the FileReader API.');
    }

    // Get the add-in web and host web URLs.
    appWebUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
    hostWebUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
});

function getQueryStringParameter(paramToRetrieve) {
    var params = document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve) return singleParam[1];
    }
}

    function F1()
    {
    window.location.href=sphosturl+'pages/uploadform.aspx';

    }



    </script>


    <div>
    <input type='button' value='clickheretoUploadfile' onclick='F1()'/>

    </div>

when the user is clicked on clickhere button is redirecting to uploadform.aspx

it is uploadform.aspx code

 <script>

    'use strict';

    jQuery(document).ready(function () {

        // Check for FileReader API (HTML5) support.
        if (!window.FileReader) {
            alert('This browser does not support the FileReader API.');
        }
    });

    // Upload the file.
    // You can upload files up to 2 GB with the REST API.
    function uploadFile() {

        // Define the folder path for this example.
        var serverRelativeUrlToFolder = '/shared documents';

        // Get test values from the file input and text input page controls.
        var fileInput = jQuery('#getFile');
        var newName = jQuery('#displayName').val();

        // Get the server URL.
        var serverUrl = _spPageContextInfo.webAbsoluteUrl;

        // Initiate method calls using jQuery promises.
        // Get the local file as an array buffer.
        var getFile = getFileBuffer();
        getFile.done(function (arrayBuffer) {

            // Add the file to the SharePoint folder.
            var addFile = addFileToFolder(arrayBuffer);
            addFile.done(function (file, status, xhr) {

                // Get the list item that corresponds to the uploaded file.
                var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
                getItem.done(function (listItem, status, xhr) {

                    // Change the display name and title of the list item.
                    var changeItem = updateListItem(listItem.d.__metadata);
                    changeItem.done(function (data, status, xhr) {
                        alert('file uploaded and updated');
                    });
                    changeItem.fail(onError);
                });
                getItem.fail(onError);
            });
            addFile.fail(onError);
        });
        getFile.fail(onError);

        // Get the local file as an array buffer.
        function getFileBuffer() {
            var deferred = jQuery.Deferred();
            var reader = new FileReader();
            reader.onloadend = function (e) {
                deferred.resolve(e.target.result);
            }
            reader.onerror = function (e) {
                deferred.reject(e.target.error);
            }
            reader.readAsArrayBuffer(fileInput[0].files[0]);
            return deferred.promise();
        }

        // Add the file to the file collection in the Shared Documents folder.
        function addFileToFolder(arrayBuffer) {

            // Get the file name from the file input control on the page.
            var parts = fileInput[0].value.split('\\');
            var fileName = parts[parts.length - 1];

            // Construct the endpoint.
            var fileCollectionEndpoint = String.format(
                    "{0}/_api/web/getfolderbyserverrelativeurl('{1}')/files" +
                    "/add(overwrite=true, url='{2}')",
                    serverUrl, serverRelativeUrlToFolder, fileName);

            // Send the request and return the response.
            // This call returns the SharePoint file.
            return jQuery.ajax({
                url: fileCollectionEndpoint,
                type: "POST",
                data: arrayBuffer,
                processData: false,
                headers: {
                    "accept": "application/json;odata=verbose",
                    "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                    "content-length": arrayBuffer.byteLength
                }
            });
        }

        // Get the list item that corresponds to the file by calling the file's ListItemAllFields property.
        function getListItem(fileListItemUri) {

            // Send the request and return the response.
            return jQuery.ajax({
                url: fileListItemUri,
                type: "GET",
                headers: { "accept": "application/json;odata=verbose" }
            });
        }

        // Change the display name and title of the list item.
        function updateListItem(itemMetadata) {

            // Define the list item changes. Use the FileLeafRef property to change the display name. 
            // For simplicity, also use the name as the title. 
            // The example gets the list item type from the item's metadata, but you can also get it from the
            // ListItemEntityTypeFullName property of the list.
            var body = String.format("{{'__metadata':{{'type':'{0}'}},'FileLeafRef':'{1}','Title':'{2}'}}",
                itemMetadata.type, newName, newName);

            // Send the request and return the promise.
            // This call does not return response content from the server.
            return jQuery.ajax({
                url: itemMetadata.uri,
                type: "POST",
                data: body,
                headers: {
                    "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                    "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);
    }

    <script>

    <input id="getFile" type="file"/><br />
    <input id="displayName" type="text" value="Enter a unique name" /><br />
    <input id="addFileButton" type="button" value="Upload" onclick="uploadFile()">

the problem is when i perform the uploading functionality in the default.aspx page it is working good.but i redirecting from that page to upload page and perform the uploading functionality it is the error

1 Answers1

0

The first question is where is your "sphosturl" parameter in the Default.aspx code? I guess it is the "appWebUrl".

From your code ,it seems you want to make your SharePoint-hosted add-in to upload files to the add-in web, so you must confirm whether you have documents library folder in your app and set correct location to "serverRelativeUrlToFolder" parameter . Otherwise it will threw Access Denied error. Tested code below is for your reference (I have add the documents library in my app):

'use strict';

jQuery(document).ready(function () {

// Check for FileReader API (HTML5) support.
   if (!window.FileReader) {
    alert('This browser does not support the FileReader API.');
   }
});

// Upload the file.
// You can upload files up to 2 GB with the REST API.
 function uploadFile() {

  // Define the folder path for this example.
  var serverRelativeUrlToFolder = 'Lists/DL';

  // Get test values from the file input and text input page controls.
  var fileInput = jQuery('#getFile');
  var newName = jQuery('#displayName').val();

  // Get the server URL.
  var serverUrl = _spPageContextInfo.webAbsoluteUrl;

  // Initiate method calls using jQuery promises.
  // Get the local file as an array buffer.
  var getFile = getFileBuffer();
  getFile.done(function (arrayBuffer) {

    // Add the file to the SharePoint folder.
    var addFile = addFileToFolder(arrayBuffer);
    addFile.done(function (file, status, xhr) {

        // Get the list item that corresponds to the uploaded file.
        var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
        getItem.done(function (listItem, status, xhr) {

            // Change the display name and title of the list item.
            var changeItem = updateListItem(listItem.d.__metadata);
            changeItem.done(function (data, status, xhr) {
                alert('file uploaded and updated');
            });
            changeItem.fail(onError);
        });
        getItem.fail(onError);
    });
    addFile.fail(onError);
});
getFile.fail(onError);

// Get the local file as an array buffer.
function getFileBuffer() {
    var deferred = jQuery.Deferred();
    var reader = new FileReader();
    reader.onloadend = function (e) {
        deferred.resolve(e.target.result);
    }
    reader.onerror = function (e) {
        deferred.reject(e.target.error);
    }
    reader.readAsArrayBuffer(fileInput[0].files[0]);
    return deferred.promise();
}

// Add the file to the file collection in the Shared Documents folder.
function addFileToFolder(arrayBuffer) {

    // Get the file name from the file input control on the page.
    var parts = fileInput[0].value.split('\\');
    var fileName = parts[parts.length - 1];

    // Construct the endpoint.
    var fileCollectionEndpoint = String.format(
            "{0}/_api/web/getfolderbyserverrelativeurl('{1}')/files" +
            "/add(overwrite=true, url='{2}')",
            serverUrl, serverRelativeUrlToFolder, fileName);

    // Send the request and return the response.
    // This call returns the SharePoint file.
    return jQuery.ajax({
        url: fileCollectionEndpoint,
        type: "POST",
        data: arrayBuffer,
        processData: false,
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
            "content-length": arrayBuffer.byteLength
        }
    });
}

// Get the list item that corresponds to the file by calling the file's  ListItemAllFields property.
function getListItem(fileListItemUri) {

    // Send the request and return the response.
    return jQuery.ajax({
        url: fileListItemUri,
        type: "GET",
        headers: { "accept": "application/json;odata=verbose" }
    });
}

// Change the display name and title of the list item.
function updateListItem(itemMetadata) {

    // Define the list item changes. Use the FileLeafRef property to change the display name. 
    // For simplicity, also use the name as the title. 
    // The example gets the list item type from the item's metadata, but you can also get it from the
    // ListItemEntityTypeFullName property of the list.
    var body = String.format("{{'__metadata':{{'type':'{0}'}},'FileLeafRef':'{1}','Title':'{2}'}}",
        itemMetadata.type, newName, newName);

    // Send the request and return the promise.
    // This call does not return response content from the server.
    return jQuery.ajax({
        url: itemMetadata.uri,
        type: "POST",
        data: body,
        headers: {
            "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
            "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);
}

enter image description here

Nan Yu
  • 26,101
  • 9
  • 68
  • 148
  • Hi @Nan Yu , i am not having problem with upload functionality, my problem is how to redirect from one page to another page in share point hosted app. –  Apr 11 '16 at 03:38
  • window.location.href=appWebUrl+'pages/uploadform.aspx' but you need to confirm you have "uploadform" page in your pages folder in app – Nan Yu Apr 11 '16 at 06:22
  • k k i will check @Nan Yu –  Apr 11 '16 at 09:08
  • hi @Nan Yu , i have one doubt in both pages sphosturl ,appweburl are same or not. –  Apr 11 '16 at 09:51
  • SPHostUrl is the host web URL,SPAppWebUrl is the app web URL .You could debug your application in vs to see the difference . – Nan Yu Apr 12 '16 at 01:27
  • hi @Nan Yu, i am asking that My first page default. aspx, when i redirected to uploadfrom.aspx, and in upload form, again we want sphosturl,spappweburl.but it through error like split method is not supported. –  Apr 12 '16 at 03:51
  • hi @Nan Yu, how to get the sphosturl,spappweburl after we redirecting from one page to another page. –  Apr 12 '16 at 04:16
  • HI, @Nan Yu, are u know the solution or not. –  Apr 12 '16 at 04:52
  • @joy, you could add the query string in the another page which you want to redirect . click this [thread](http://sharepoint.stackexchange.com/questions/175701/sharepoint-hosted-app-get-hostweburl-and-appweburl-on-navigation) for reference . – Nan Yu Apr 12 '16 at 05:32