如何在站点和子站点之间使用 Sharepoint 2013 中的 Rest API 和 javascript 复制文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16942008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to copy file using Rest API and javascript in Sharepoint 2013 between site and subsite
提问by qw141
I need to copy file between document libraries. Library A is located in one site and Library B is located in subsite. I know how to copy file between libraries on the same level but the problem is with copying between different level.
我需要在文档库之间复制文件。图书馆 A 位于一个站点,图书馆 B 位于子站点。我知道如何在同一级别的库之间复制文件,但问题在于在不同级别之间复制。
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?
它不起作用。如何解决这个问题?
回答by John Milan
Just figured this one out today for the cross site solution. The trick is-- don't use $.ajax for the download of the document. Use good old XMLHttpRequest. The reason is that JQuery simply doesn't let you get a raw binary data array from SharePoint. But, the XMLHttpRequest does because it allows you to get an arraybuffer as part of its implementation, which SharePoint accepts!
今天刚刚为跨站点解决方案解决了这个问题。诀窍是——不要使用 $.ajax 来下载文档。使用旧的 XMLHttpRequest。原因是 JQuery 根本不允许您从 SharePoint 获取原始二进制数据数组。但是,XMLHttpRequest 这样做是因为它允许您将数组缓冲区作为其实现的一部分,SharePoint 接受它!
The following is the code with the parts identified for building the full source and target REST urls. Note that you can use $.ajax to upload the file.
以下是包含用于构建完整源和目标 REST url 的部分的代码。请注意,您可以使用 $.ajax 上传文件。
- sourceSiteis a sharepoint site suitable for appending the '_api' rest endpoint
- sourceFolderPathis the relative folder path your document is located within
- sourceFileNameis the filename of the document
- targetSite, targetFolderPathand targetFileNameare the mirror images or source, only for the destination.
requestDigestis that special value you need for SharePoint to accept updates.
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(); }
- sourceSite是一个适合附加“_api”休息端点的共享点站点
- sourceFolderPath是文档所在的相对文件夹路径
- sourceFileName是文档的文件名
- targetSite、targetFolderPath和targetFileName是镜像或源,仅用于目的地。
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(); }
回答by PowerSupply
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. Fetch a matching RequestDigest by calling '_api/contextinfo' on your target location.
您的问题的一个可能原因是您的 RequestDigest 与您要发布文件的位置不匹配,因为它是从运行代码的页面中获取的。通过在目标位置调用“_api/contextinfo”来获取匹配的 RequestDigest。
See: http://blogs.breeze.net/mickb/2012/11/20/SP2013GettingAFormDigestForUpdateRESTCalls.aspxand http://msdn.microsoft.com/en-us/magazine/dn198245.aspx(writing to Sharepoint section)
请参阅:http: //blogs.breeze.net/mickb/2012/11/20/SP2013GettingAFormDigestForUpdateRESTCalls.aspx和 http://msdn.microsoft.com/en-us/magazine/dn198245.aspx(写入 Sharepoint 部分)
回答by kannan
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
回答by Vinod kumar G
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,用于 post 操作的示例 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);
}
});
回答by George Livingston
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)
注意:如果列表项是新创建的,则上述功能将不起作用。但是对于所有其他情况,它都可以工作(甚至将一个文档库形成到另一个文档库或跨站点/站点集合)