How to copy files between sites using JavaScript REST in Office365 / SharePoint 2013

本文介绍如何使用JavaScript和REST API在不同SharePoint站点间复制文件。文章详细解释了通过读取文件内容并将其作为二进制数据上传到目标站点的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://techmikael.blogspot.in/2013/07/how-to-copy-files-between-sites-using.html

I’m currently playing with a POC for an App, and wanted to try to do the App as a SharePoint hosted one, only using JavaScript and REST.
The starting point was to call _vti_bin/ExcelRest.asmx on the host web from my app web, but this end-point does neither support CORS nor JSONP, so it can’t be used directly. My next thought was; Ok, let’s copy the file from the host web over to my app web, then call ExcelRest locally. Easier said than done!
While the final solution seems easy enough, the research, trial and error have taken me about 3 days. I’m now sharing this with you so you can spend your valuable time increasing the international GDP instead.
Note: If you want to copy files between two libraries on the same level, then you can use the copyTo method. http://server/site/_api/web/folders/GetByUrl('/site/srclib')/Files/getbyurl('madcow.xlsx')/copyTo(strNewUrl = '/site/targetlib/madcow.xlsx,bOverWrite = true)

Problem
Copy a file from a document library in one site to a document library in a different site using JavaScript and REST.
The code samples have URL’s using the App web proxy, but it’s easily modifiable for non-app work as well.
Step 1 – Reading the file

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

var hostweburl = decodeURIComponent(getParameterByName('SPHostUrl'));

var appweburl = decodeURIComponent(getParameterByName('SPAppWebUrl'));

var fileContentUrl = "_api/SP.AppContextSite(@target)/web/GetFileByServerRelativeUrl('/site/library/madcow.xlsx')/$value?@target='" + hostweburl + "'";

var executor = new SP.RequestExecutor(appweburl);

var info = {

url: fileContentUrl,

method: "GET",

binaryStringResponseBody: true,

success: function (data) {

//binary data available in data.body

var result = data.body;

},

error: function (err) {

alert(JSON.stringify(err));

}

};

executor.executeAsync(info);

The important parameter here is setting binaryStringResponseBody to true. Without this parameter the response is being decoded as UTF-8 and the result in the success callback is garbled data, which leads to a corrupt file on save.
The  binaryStringResponseBody parameter is not documented anywhere, but I stumbled upon binaryStringRequestbody in an msdn article which was used when uploading a file, and I figured it was worth a shot. Opening SP.RequestExecutor.debug.js I indeed found this parameter.

Step 2 – Patching SP.RequestExecutor.debug.js
Adding binaryStringResponseBody will upon return of the call cause a script error as seen in the figure below.
image
The method in question is reading over the response byte-by-byte from an Uint8Array, building a correctly encoded string. The issue is that it tries to concatenate to a variable named ret, which is not defined. The defined variable is named $v_0, and here we have a real bug in the script. The bug is there both in Office365 and SharePoint 2013 on-premise.
Luckily for us patching JavaScript is super easy. You merely override the methods involved somewhere in your own code before it’s being called. In the below sample it’s being called once the SP.RequestExecutor.js library has been loaded. The method named BinaryDecode is the one with the error, but you have to override more methods as the originator called is internalProcessXMLHttpRequestOnreadystatechange, and it cascades to calling other internal functions which can be renamed at random as the method names are autogenerated. (This happened for me today and I had to change just overrinding the first function).

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

$.getScript(scriptbase + "SP.RequestExecutor.js", function(){

SP.RequestExecutorInternalSharedUtility.BinaryDecode = function SP_RequestExecutorInternalSharedUtility$BinaryDecode(data) {

var ret = '';

if (data) {

var byteArray = new Uint8Array(data);

for (var i = 0; i < data.byteLength; i++) {

ret = ret + String.fromCharCode(byteArray[i]);

}

}

;

return ret;

};

SP.RequestExecutorUtility.IsDefined = function SP_RequestExecutorUtility$$1(data) {

var nullValue = null;

return data === nullValue || typeof data === 'undefined' || !data.length;

};

SP.RequestExecutor.ParseHeaders = function SP_RequestExecutor$ParseHeaders(headers) {

if (SP.RequestExecutorUtility.IsDefined(headers)) {

return null;

}

var result = {};

var reSplit = new RegExp('\r?\n');

var headerArray = headers.split(reSplit);

for (var i = 0; i < headerArray.length; i++) {

var currentHeader = headerArray[i];

if (!SP.RequestExecutorUtility.IsDefined(currentHeader)) {

var splitPos = currentHeader.indexOf(':');

if (splitPos > 0) {

var key = currentHeader.substr(0, splitPos);

var value = currentHeader.substr(splitPos + 1);

key = SP.RequestExecutorNative.trim(key);

value = SP.RequestExecutorNative.trim(value);

result[key.toUpperCase()] = value;

}

}

}

return result;

};

SP.RequestExecutor.internalProcessXMLHttpRequestOnreadystatechange = function SP_RequestExecutor$internalProcessXMLHttpRequestOnreadystatechange(xhr, requestInfo, timeoutId) {

if (xhr.readyState === 4) {

if (timeoutId) {

window.clearTimeout(timeoutId);

}

xhr.onreadystatechange = SP.RequestExecutorNative.emptyCallback;

var responseInfo = new SP.ResponseInfo();

responseInfo.state = requestInfo.state;

responseInfo.responseAvailable = true;

if (requestInfo.binaryStringResponseBody) {

responseInfo.body = SP.RequestExecutorInternalSharedUtility.BinaryDecode(xhr.response);

}

else {

responseInfo.body = xhr.responseText;

}

responseInfo.statusCode = xhr.status;

responseInfo.statusText = xhr.statusText;

responseInfo.contentType = xhr.getResponseHeader('content-type');

responseInfo.allResponseHeaders = xhr.getAllResponseHeaders();

responseInfo.headers = SP.RequestExecutor.ParseHeaders(responseInfo.allResponseHeaders);

if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 1223) {

if (requestInfo.success) {

requestInfo.success(responseInfo);

}

}

else {

var error = SP.RequestExecutorErrors.httpError;

var statusText = xhr.statusText;

if (requestInfo.error) {

requestInfo.error(responseInfo, error, statusText);

}

}

}

};

});

Step 3 – Uploading the file
The next step is to save the file in a library on my app web. The crucial part again is to make sure the data is being treated as binary, this time with binaryStringRequestBody set to true. Make a note of the digest variable as well. On a page inheriting the SP masterpage you can get this value with $("#__REQUESTDIGEST").val(). If not then you have to execute a separate call to _api/contextinfo. The code for that is at the bottom of this post.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

var appweburl = decodeURIComponent(getParameterByName('SPAppWebUrl'));

var executor = new SP.RequestExecutor(appweburl);

var info = {

url: "_api/web/GetFolderByServerRelativeUrl('/appWebtargetFolder')/Files/Add(url='madcow.xlsx', overwrite=true)",

method: "POST",

headers: {

"Accept": "application/json; odata=verbose",

"X-RequestDigest": digest

},

contentType: "application/json;odata=verbose",

binaryStringRequestBody: true,

body: arrayBuffer,

success: function(data) {

alert("Success! Your file was uploaded to SharePoint.");

},

error: function (err) {

alert("Oooooops... it looks like something went wrong uploading your file.");

}

};

executor.executeAsync(info);

Journey
I started out using jQuery.ajax for my REST calls, but I did not manage to get the encoding right no matter how many posts I read on this. I read through a lot on the following links which led me to the final solution:
Get the digest value

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

$.ajax({

url: "_api/contextinfo",

type: "POST",

contentType: "application/x-www-url-encoded",

dataType: "json",

headers: {

"Accept": "application/json; odata=verbose",

},

success: function (data) {

if (data.d) {

var digest = data.d.GetContextWebInformation.FormDigestValue;

}

},

error: function (err) {

alert(JSON.stringify(err));

}

});

转载于:https://www.cnblogs.com/frankzye/p/3374475.html

1. 用户与身体信息管理模块 用户信息管理: 注册登录:支持手机号 / 邮箱注册,密码加密存储,提供第三方快捷登录(模拟) 个人资料:记录基本信息(姓名、年龄、性别、身高、体重、职业) 健康目标:用户设置目标(如 “减重 5kg”“增肌”“维持健康”)及期望周期 身体状态跟踪: 体重记录:定期录入体重数据,生成体重变化曲线(折线图) 身体指标:记录 BMI(自动计算)、体脂率(可选)、基础代谢率(根据身高体重估算) 健康状况:用户可填写特殊情况(如糖尿病、过敏食物、素食偏好),系统据此调整推荐 2. 膳食记录与食物数据库模块 食物数据库: 基础信息:包含常见食物(如米饭、鸡蛋、牛肉)的名称、类别(主食 / 肉类 / 蔬菜等)、每份重量 营养成分:记录每 100g 食物的热量(kcal)、蛋白质、脂肪、碳水化合物、维生素、矿物质含量 数据库维护:管理员可添加新食物、更新营养数据,支持按名称 / 类别检索 膳食记录功能: 快速记录:用户选择食物、输入食用量(克 / 份),系统自动计算摄入的营养成分 餐次分类:按早餐 / 午餐 / 晚餐 / 加餐分类记录,支持上传餐食照片(可选) 批量操作:提供常见套餐模板(如 “三明治 + 牛奶”),一键添加到记录 历史记录:按日期查看过往膳食记录,支持编辑 / 删除错误记录 3. 营养分析模块 每日营养摄入分析: 核心指标计算:统计当日摄入的总热量、蛋白质 / 脂肪 / 碳水化合物占比(按每日推荐量对比) 微量营养素分析:检查维生素(如维生素 C、钙、铁)的摄入是否达标 平衡评估:生成 “营养平衡度” 评分(0-100 分),指出摄入过剩或不足的营养素 趋势分析: 周 / 月营养趋势:用折线图展示近 7 天 / 30 天的热量、三大营养素摄入变化 对比分析:将实际摄入与推荐量对比(如 “蛋白质摄入仅达到推荐量的 70%”) 目标达成率:针对健
To split a DOCX file into multiple DOCX files by title using docx4j, you can follow these steps: 1. Load the original DOCX file using docx4j. 2. Iterate through the document's paragraphs and identify the paragraphs that represent titles/headings. You can use the paragraph's style or any other identifying feature to determine the titles. 3. For each title paragraph, create a new DOCX file. 4. Copy all the paragraphs from the original document until you encounter the next title paragraph. Add these paragraphs to the newly created DOCX file. 5. Save the newly created DOCX file. Here's a sample code snippet to demonstrate this process: ```java import org.docx4j.Docx4J; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; import org.docx4j.wml.Body; import org.docx4j.wml.Document; import org.docx4j.wml.P; import java.io.File; public class DocxSplitter { public static void main(String[] args) { try { // Load the original DOCX file WordprocessingMLPackage wordMLPackage = Docx4J.load(new File("input.docx")); Document document = wordMLPackage.getMainDocumentPart().getJaxbElement(); Body body = document.getBody(); // Iterate through paragraphs to split by title String currentTitle = null; WordprocessingMLPackage currentPackage = null; for (Object obj : body.getContent()) { if (obj instanceof P) { P paragraph = (P) obj; String style = paragraph.getPPr().getPStyle().getVal(); if (style.equals("Title")) { // Start a new DOCX file for the title if (currentPackage != null) { String fileName = currentTitle +
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值