【问题标题】:Uploading a file using shrepoint hosted app with REST API使用带有 REST API 的 sharepoint 托管应用程序上传文件
【发布时间】:2016-04-12 17:03:19
【问题描述】:

我收到错误,例如无法在共享点托管应用程序中访问该网站。 当我在同一个应用程序中将页面从一个页面移动到另一个页面时会发生这种情况。请提前帮助我

是 Default.aspx 代码

  <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

是uploadform.aspx 代码

 <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()">

问题是当我在 default.aspx 页面中执行上传功能时,它运行良好。但是我从该页面重定向到上传页面并执行上传功能,这是错误

【问题讨论】:

    标签: office365-restapi sharepoint-jsom


    【解决方案1】:

    第一个问题是 Default.aspx 代码中的“sphosturl”参数在哪里?我猜是“appWebUrl”。

    从您的代码看来,您似乎想让 SharePoint 托管的加载项将文件上传到加载项 Web,因此您必须确认您的应用中是否有文档库文件夹并将正确的位置设置为“serverRelativeUrlToFolder “ 范围 。否则会抛出拒绝访问错误。下面的测试代码供您参考(我已经在我的应用程序中添加了文档库):

    '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);
    }
    

    【讨论】:

    • 嗨@Nan Yu,我的上传功能没有问题,我的问题是如何在共享点托管应用程序中从一个页面重定向到另一个页面。
    • window.location.href=appWebUrl+'pages/uploadform.aspx' 但您需要确认您在应用程序的 pages 文件夹中有“uploadform”页面
    • k k 我会检查@Nan Yu
    • 嗨@Nan Yu,我怀疑两个页面的shosturl,appweburl是否相同。
    • SPHostUrl 是主机网址,SPAppWebUrl 是应用程序网址。您可以在 vs 中调试您的应用程序以查看差异。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    相关资源
    最近更新 更多