简体   繁体   English

如何在站点和子站点之间使用Sharepoint 2013中的Rest API和javascript复制文件

[英]How to copy file using Rest API and javascript in Sharepoint 2013 between site and subsite

I need to copy file between document libraries. 我需要在文档库之间复制文件。 Library A is located in one site and Library B is located in subsite. 图书馆A位于一个站点,图书馆B位于子站点。 I know how to copy file between libraries on the same level but the problem is with copying between different level. 我知道如何在同一级别的库之间复制文件,但问题是在不同级别之间复制。

The code I use to copy file between libraries on the same level. 我用来在同一级别的库之间复制文件的代码。

 $.ajax({
     url : "http://xxx/PWA/_api/web/folders/GetByUrl('/PWA/CopyFromLibrary')/Files/getbyurl('Import.csv')/copyTo(strNewUrl = '/PWA/TargetLibrary/Import.csv',bOverWrite = true)",

method: 'POST',
    headers: {
        "Accept": "application/json; odata=verbose",
        "X-RequestDigest":  $("#__REQUESTDIGEST").val()
    },
    success: function () {
        alert("Success! Your file was copied properly");
    },
    error: function () {
        alert("Problem with copying");
    }
    });

For different level I use just another target URL: 对于不同的级别,我只使用另一个目标URL:

url : "http://xxx/PWA/_api/web/folders/GetByUrl('/PWA/CopyFromLibrary')/Files/getbyurl('Import.csv')/copyTo(strNewUrl = '/PWA/Subsite/TargetLibrary/Import.csv',bOverWrite = true)",

And it doesn't work. 它不起作用。 How to work around this problem? 如何解决这个问题?

Just figured this one out today for the cross site solution. 今天刚刚为跨站点解决方案找到了这个。 The trick is-- don't use $.ajax for the download of the document. 诀窍是 - 不要使用$ .ajax下载文档。 Use good old XMLHttpRequest. 使用好的旧XMLHttpRequest。 The reason is that JQuery simply doesn't let you get a raw binary data array from SharePoint. 原因是JQuery根本不允许您从SharePoint获取原始二进制数据数组。 But, the XMLHttpRequest does because it allows you to get an arraybuffer as part of its implementation, which SharePoint accepts! 但是,XMLHttpRequest之所以这样做,是因为它允许您将数组缓冲作为其实现的一部分,SharePoint接受它!

The following is the code with the parts identified for building the full source and target REST urls. 以下是标识用于构建完整源和目标REST URL的部分的代码。 Note that you can use $.ajax to upload the file. 请注意,您可以使用$ .ajax上传文件。

  • sourceSite is a sharepoint site suitable for appending the '_api' rest endpoint sourceSite是一个适合附加'_api'休息端点的sharepoint站点
  • sourceFolderPath is the relative folder path your document is located within sourceFolderPath是文档所在的相对文件夹路径
  • sourceFileName is the filename of the document sourceFileName是文档的文件名
  • targetSite , targetFolderPath and targetFileName are the mirror images or source, only for the destination. targetSitetargetFolderPathtargetFileName是镜像或源,仅用于目标。
  • requestDigest is that special value you need for SharePoint to accept updates. requestDigest是SharePoint接受更新所需的特殊值。

     function copyDocument(sourceSite, sourceFolderPath, sourceFileName, targetSite, targetFolderPath, targetFileName, requestDigest) { var sourceSiteUrl = sourceSite + "_api/web/GetFolderByServerRelativeUrl('" + sourceFolderPath + "')/Files('" + sourceFileName + "')/$value"; var targetSiteUrl = targetSite + "_api/web/GetFolderByServerRelativeUrl('" + targetFolderPath + "')/Files/Add(url='" + targetFileName + "',overwrite=true)"; var xhr = new XMLHttpRequest(); xhr.open('GET', sourceSiteUrl, true); xhr.setRequestHeader('binaryStringResponseBody', true); xhr.responseType = 'arraybuffer'; xhr.onload = function (e) { if (this.status == 200) { var arrayBuffer = this.response; $.ajax({ url: targetSiteUrl, method: 'POST', data: arrayBuffer, processData: false, headers: { 'binaryStringRequestBody': 'true', 'Accept': 'application/json;odata=verbose;charset=utf-8', 'X-RequestDigest': requestDigest } }) .done(function (postData) { console.log('we did it!'); }) .fail(function (jqXHR, errorText) { console.log('dadgummit'); }); } } xhr.send(); } 

What kind of error are you getting? 你得到什么样的错误?

One probable cause of your problem is that your RequestDigest does not match the location where you want to POST your file since it is fetched from the page where your code is running. 导致问题的一个可能原因是,您的RequestDigest与您要发送文件的位置不匹配,因为它是从运行代码的页面获取的。 Fetch a matching RequestDigest by calling '_api/contextinfo' on your target location. 通过在目标位置调用“_api / contextinfo”来获取匹配的RequestDigest。

See: http://blogs.breeze.net/mickb/2012/11/20/SP2013GettingAFormDigestForUpdateRESTCalls.aspx and http://msdn.microsoft.com/en-us/magazine/dn198245.aspx (writing to Sharepoint section) 请参阅: http//blogs.breeze.net/mickb/2012/11/20/SP2013GettingAFormDigestForUpdateRESTCalls.aspxhttp://msdn.microsoft.com/en-us/magazine/dn198245.aspx (写入Sharepoint部分)

Note File Move operations only work within the scope of a given document library. 注意文件移动操作仅在给定文档库的范围内工作。 You cannot copy between document libraries. 您无法在文档库之间进行复制。

http://msdn.microsoft.com/en-us/library/office/dn605900(v=office.15).aspx#Folder6 http://msdn.microsoft.com/en-us/library/office/dn605900(v=office.15).aspx#Folder6

For POST - operation we need request digest value, which is used by SharePoint to authenticate mainly for Post, Delete, Update not needed for GET operation, Sample jquery ajax code for post operation- 对于POST操作,我们需要请求摘要值,SharePoint使用它来主要验证GET操作不需要的Post,Delete,Update,后续操作的示例jquery ajax代码 -

 $.ajax({
        url: url + "/_api/web/lists/getbytitle('" + listname + "')/items",
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
            success(data); // Returns the newly created list item information
        },
        error: function (data) {
            failure(data);
        }
    });

You can try the following code for copying file from one location to another within SharePoint. 您可以尝试以下代码将文件从SharePoint中的一个位置复制到另一个位置。

The following example will be helpful in copying files within SharePoint sandbox. 以下示例将有助于在SharePoint沙箱中复制文件。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myapp" ng-controller="mycont">
    <input type="button" ng-click = "myclick()" value="Angular File Copy" />    
</div>

<input type=button onclick="x()"  value="jQueryFile copy" />
<script>
    var dt =new Date();
    var val_ue = dt.getDate()+""+dt.getHours()+""+dt.getMinutes()+""+dt.getSeconds() +"1" ;
    var url1 = "/_api/web/getfilebyserverrelativeurl('/Lists/Document_Mapping/Attachments/1/9.jpg')";
    var url2 = "/Lists/AddressVersioning/Attachments/84/" ;
    var combined = "";
    var app = angular.module('myapp',[]);
    var _headers = {
        'X-RequestDigest': document.getElementById("__REQUESTDIGEST").value,
        'accept':'application/json;odata=verbose'
    };
    app.controller('mycont',function($scope,$http){
        $scope.myclick =  function(){
            combined = url1 + "/copyTo('" + url2 + val_ue + ".jpg')";
            $http({method:'POST',url:combined,headers:_headers}).then(
                function(response){
                    console.log("hi");
                    val_ue += 1;
                },
                function(error){
                    console.log("Error:");
                    console.log(error);
                },
                function(process){
                    console.log("process:");
                    console.log(process);
                }
            );
        }
    });
    var x = function(){
        combined = url1 + "/copyTo('" + url2 + val_ue + ".jpg')";
        $.ajax({
            url : combined,
            method: 'POST',
            headers: {
                "Accept": "application/json; odata=verbose",
                "X-RequestDigest":  $("#__REQUESTDIGEST").val()
            },
            success: function () {
                alert("Success! Your file was copied properly");
                val_ue +=1;
            },
            error: function () {
                alert("Problem with copying");
            }
        });
    }
</script>

Note: the above function will not work if the list item is newly created. 注意:如果新创建了列表项,则上述功能将不起作用。 But for all other situations it will work (even form one doc library to another doc library or cross site / site collection) 但对于所有其他情况,它将工作(甚至形成一个文档库到另一个文档库或跨站点/网站集)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 公开Sharepoint 2013 REST API使用JavaScript获取 - Exposing Sharepoint 2013 REST API Get using JavaScript 使用REST API将文件签入到Sharepoint 2013不起作用 - Check In of file using REST API to Sharepoint 2013 not working Sharepoint如何识别当前站点是根站点还是子站点(子站点级别)? - Sharepoint How to identify your current site is rootsite or subsite (level of subsite)? 以编程方式在SharePoint 2013中创建子网站 - Create subsite in SharePoint 2013 programmatically 如何使用REST for Sharepoint 2013删除项目 - How to delete an item using REST for Sharepoint 2013 如何使用JavaScript / JQuery在面向公众的ASP.NET网站上使用SP2013 REST API? - How to use SP2013 REST API on public-facing ASP.NET site using JavaScript/JQuery? 从SharePoint 2013 REST API对文件使用moveto或copyto时出现“格式不正确的JSON流” - “Not well formed JSON stream” when using moveto or copyto on file from SharePoint 2013 REST API 使用iPad的sharepoint 2013创建的网站有时未加载一些javascript文件 - sharepoint 2013 created site with ipad sometimes a few javascript file not loaded SharePoint 2013 Library检索所有文件名。 REST API - SharePoint 2013 Library retrieving all file names. REST API 无法使用COM javascript访问sharepoint 2013网站 - Unable to access sharepoint 2013 site using COM javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM