当前位置: 首页 > news >正文

SharePoint REST API - 使用REST API和jQuery上传一个文件

博客地址:http://blog.csdn.net/FoxDave

本篇主要通过两个代码示例来展示如何应用REST API和jQuery上传文件到SharePoint。

示例会使用REST接口和jQuery AJAX请求来将一个本地文件添加到SharePoint文档库并修改它的一些属性。主要有以下几个操作步骤:

1. 使用FileReader API将本地文件转换成数组(需要HTML5支持),jQuery的(document).ready函数会检查浏览器对FileReader API的支持情况。

2. 使用文件夹的文件集合对象的Add方法将文件添加到文档库,将数组缓冲放到POST请求的body里。本文介绍的示例会使用getfolderbyserverrelativeurl端点来获取文件集合对象,如果不用这个,你也可以使用列表端点如…/_api/web/lists/getbytitle('<list title>')/rootfolder/files/add。

3. 使用ListItemAllFields属性来获取与上传文件相对应的列表项。

4. 使用MERGE请求来更改列表项的标题和显示名。

运行代码示例

本文中的两个代码示例使用REST API和jQuery AJAX请求来上传文件到文档库,然后更改对应列表项的属性。第一个例子使用SP.AppContextSite来跨SharePoint域进行调用,就像SharePoint承载的Add-in在上传文件到承载它的网站时做的那样。另一个例子是在同域调用的,就像上传到Add-in所在的网站时做的那样。

注意用JavaScript编写的提供程序承载的Add-in必须使用SP.RequestExecutor跨域库来向SharePoint域发送请求。

使用本文提到的示例,你需要做以下事情:

1. 首先你要有SharePoint Server 2013、2016或者是Online的环境。

2. 执行代码的用户需要有对文档库的写权限,如果你开发的是一个SharePoint Add-in的话,你可以在列表范围指定写权限。

3. 支持FileReader API(HTML5)的浏览器。

4. 在你的页面中引用jQuery库,例如:

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>
5. 在你的页面中添加以下控件:

<input id="getFile" type="file"/><br />
  <input id="displayName" type="text" value="Enter a unique name" /><br />
  <input id="addFileButton" type="button" value="Upload" οnclick="uploadFile()"/>
代码示例一:使用REST API和jQuery跨SharePoint域上传文件

大师傅下面的代码示例将文件上传到承载SharePoint Add-in的SharePoint网站。

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

// 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.
    // The display name must be unique every time you run the example.
    var fileInput = jQuery('#getFile');
    var newName = jQuery('#displayName').val();

    // 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/sp.appcontextsite(@target)/web/getfolderbyserverrelativeurl('{1}')/files" +
            "/add(overwrite=true, url='{2}')?@target='{3}'",
            appWebUrl, serverRelativeUrlToFolder, fileName, hostWebUrl);

        // 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) {

        // Construct the endpoint.
        // The list item URI uses the host web, but the cross-domain call is sent to the
        // add-in web and specifies the host web as the context site.
        fileListItemUri = fileListItemUri.replace(hostWebUrl, '{0}');
        fileListItemUri = fileListItemUri.replace('_api/Web', '_api/sp.appcontextsite(@target)/web');
        
        var listItemAllFieldsEndpoint = String.format(fileListItemUri + "?@target='{1}'",
            appWebUrl, hostWebUrl);

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

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

        // Construct the endpoint.
        // Specify the host web as the context site.
        var listItemUri = itemMetadata.uri.replace('_api/Web', '_api/sp.appcontextsite(@target)/web');
        var listItemEndpoint = String.format(listItemUri + "?@target='{0}'", hostWebUrl);

        // 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: listItemEndpoint,
            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);
}

// Get parameters from the query string.
// For production purposes you may want to use a library to handle the query string.
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];
    }
}
代码示例二:使用REST API和jQuery将文件上传到同域网站
'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);
}
本篇就到这里。

转载于:https://www.cnblogs.com/justinliu/p/7703743.html

相关文章:

  • localStorage小结
  • scrum学习心得
  • Mysql字符集设置
  • httpclient连接池
  • JS判断键盘是否按的回车键并触发指定按钮点击操作
  • 根据ip抓 包
  • Mac下Tomcat安装配置80默认端口设置
  • Jzoj4699 Password
  • (十)T检验-第一部分
  • [Bzoj4722]由乃(线段树好题)(倍增处理模数小快速幂)
  • JAVA-JSP内置对象之request对象的其他方法
  • SVN冲突解决
  • JavaScript table动态生成数据
  • python-爬虫day1
  • 调用自定义验证码出现的问题
  • [译]前端离线指南(上)
  • es6--symbol
  • JavaScript 一些 DOM 的知识点
  • Linux CTF 逆向入门
  • MyEclipse 8.0 GA 搭建 Struts2 + Spring2 + Hibernate3 (测试)
  • PAT A1050
  • Python_OOP
  • Python爬虫--- 1.3 BS4库的解析器
  • SpiderData 2019年2月13日 DApp数据排行榜
  • web标准化(下)
  • Windows Containers 大冒险: 容器网络
  • 阿里云爬虫风险管理产品商业化,为云端流量保驾护航
  • - 概述 - 《设计模式(极简c++版)》
  • 可能是历史上最全的CC0版权可以免费商用的图片网站
  • 深度解析利用ES6进行Promise封装总结
  • 腾讯大梁:DevOps最后一棒,有效构建海量运营的持续反馈能力
  • 腾讯视频格式如何转换成mp4 将下载的qlv文件转换成mp4的方法
  • 文本多行溢出显示...之最后一行不到行尾的解决
  • 原生 js 实现移动端 Touch 滑动反弹
  • (C++)栈的链式存储结构(出栈、入栈、判空、遍历、销毁)(数据结构与算法)
  • (笔试题)合法字符串
  • (附源码)node.js知识分享网站 毕业设计 202038
  • (规划)24届春招和25届暑假实习路线准备规划
  • (论文阅读26/100)Weakly-supervised learning with convolutional neural networks
  • (欧拉)openEuler系统添加网卡文件配置流程、(欧拉)openEuler系统手动配置ipv6地址流程、(欧拉)openEuler系统网络管理说明
  • (算法)求1到1亿间的质数或素数
  • (轉貼) 資訊相關科系畢業的學生,未來會是什麼樣子?(Misc)
  • .bat批处理(十一):替换字符串中包含百分号%的子串
  • .jks文件(JAVA KeyStore)
  • .NET Framework 和 .NET Core 在默认情况下垃圾回收(GC)机制的不同(局部变量部分)
  • .NET6实现破解Modbus poll点表配置文件
  • .NET中统一的存储过程调用方法(收藏)
  • .sh
  • @Autowired自动装配
  • [ 2222 ]http://e.eqxiu.com/s/wJMf15Ku
  • [ 环境搭建篇 ] 安装 java 环境并配置环境变量(附 JDK1.8 安装包)
  • [1159]adb判断手机屏幕状态并点亮屏幕
  • [20150707]外部表与rowid.txt
  • [Android 数据通信] android cmwap接入点
  • [Android开源]EasySharedPreferences:优雅的进行SharedPreferences数据存储操作