http://www.shillier.com/archive/2013/03/26/uploading-files-in-sharepoint-2013-using-csom-and-rest.aspx

 

Recently, I have been working through the process of trying to accomplish as many basic SharePoint tasks with both CSOM and REST as possible. My goal is to build a deeper understanding of what operations work in both approaches as well as strengths and limitations. In the case of document uploading, the CSOM approach is only good for files up to 1.5MB whereas REST is good up to 2GB. This makes understanding the REST approach critical, but I was struggling to get it working using the jQuery ajax method because the documentation is not great. In this post, I’ll save you the heartache I went through and just show you how to do it in both approaches.

Selecting Files

The first thing to set up is the control used for selecting files from the web page. This is a pretty simple use ofinput controls:

<input id="inputFile" type="file" />

<input id="uploadDocumentButton" type="Button" value="Upload Document"/>

The inputFile control allows for the browsing and selecting of files. The uploadDocumentButton control initiates the upload process. The inputFile control has a Files collection that you can use to access the file for uploading. The following code shows how to get the filename and file for uploading.

$("#uploadDocumentButton").click(function () {

if (document.getElementById("inputFile").files.length === 0) {

alert("Select a file!");

return;

}

var parts = document.getElementById("inputFile").value.split("\\");

var filename = parts[parts.length - 1];

var file = document.getElementById("inputFile").files[0];

}

Reading Files

Once the file is selected, you have to read the bytes into your JavaScript code. This is accomplished using theFileReader object. This object accepts the file information for loading asynchronously. The onload and onerrorevents fire when the file is loaded successfully or fails. I wrote a helper function using promises to read the file into an ArrayBuffer, which will be used later during the upload.

var getFileBuffer = function (file) {

var deferred = $.Deferred();

var reader = new FileReader();

reader.onload = function (e) {

deferred.resolve(e.target.result);

}

reader.onerror = function (e) {

deferred.reject(e.target.error);

}

reader.readAsArrayBuffer(file);

return deferred.promise();

};

Uploading with CSOM

Uploading the file with CSOM requires converting the ArrayBuffer to a Base64-encoded array, which is then put into a SP.FileCreationInformation object. The following code shows a complete library for uploading with CSOM.

"use strict";

var WingtipToys = window.WingtipToys || {};

WingtipToys.Jsom = WingtipToys.Jsom || {};

WingtipToys.Jsom.Libs = function () {

var deferreds = new Array(),

upload = function (serverRelativeUrl, filename, file) {

deferreds[deferreds.length] = $.Deferred();

getFileBuffer(file).then(

function (buffer) {

var bytes = new Uint8Array(buffer);

var content = new SP.Base64EncodedByteArray(); //base64 encoding

for (var b = 0; b < bytes.length; b++) {

content.append(bytes[b]);

}

var ctx = new SP.ClientContext.get_current();

var createInfo = new SP.FileCreationInformation();

createInfo.set_content(content); //setting the content of the new file

createInfo.set_overwrite(true);

createInfo.set_url(filename);

this.files = ctx.get_web().getFolderByServerRelativeUrl(serverRelativeUrl).get_files();

ctx.load(this.files);

this.files.add(createInfo);

ctx.executeQueryAsync(

Function.createDelegate(this,

function () { deferreds[deferreds.length - 1].resolve(this.files); }),

Function.createDelegate(this,

function (sender, args) { deferreds[deferreds.length - 1].reject(sender, args); }));

},

function (err) {

deferreds[deferreds.length - 1].reject(err);

}

);

return deferreds[deferreds.length - 1].promise();

},

getFileBuffer = function (file) {

//See previous code

};

return {

upload: upload,

};

}();

Once the library is written, uploading the file becomes pretty simple. For this example, I am assuming a document library named “JSOM Documents” exists. Notice how the server-relative URL is provided to the upload method.

WingtipToys.Jsom.Libs.upload("/apps/LibraryOperations/JSOM%20Documents", filename, file)

.then(

function (files) {

alert("Uploaded successfully");

},

function (sender, args) {

alert(args.get_message());

}

);

Uploading with REST

The REST approach can use the contents of the ArrayBuffer directly. The key to making this approach work with jQuery ajax is to set the processData flag to false. By default, jQuery ajax will process all non-string data into a query string, which corrupts the binary file data during the upload. By setting it to false, the data is faithfully uploaded. The following code shows a complete library for uploading with REST.

"use strict";

var WingtipToys = window.WingtipToys || {};

WingtipToys.Rest = WingtipToys.Rest || {};

WingtipToys.Rest.Libs = function () {

var upload = function (serverRelativeUrl, filename, file) {

var deferred = $.Deferred();

getFileBuffer(file).then(

function (arrayBuffer) {

$.ajax({

url: _spPageContextInfo.webServerRelativeUrl +

"/_api/web/GetFolderByServerRelativeUrl('" + serverRelativeUrl + "')/Files" +

"/Add(url='" + filename + "', overwrite=true)",

type: "POST",

data: arrayBuffer,

processData: false,

headers: {

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

"X-RequestDigest": $("#__REQUESTDIGEST").val(),

"content-length": arrayBuffer.byteLength

},

success: function (data) {

deferred.resolve(data);

},

error: function (err) {

deferred.reject(err);

}

});

},

function (err) {

deferred.reject(err);

}

);

return deferred.promise();

},

getFileBuffer = function (file) {

//See previous code

};

return {

upload: upload

};

}();

Again, once you have the library, uploading the file is easy. Here is the REST version of the upload method.

WingtipToys.Rest.Libs.upload("/apps/LibraryOperations/REST%20Documents", filename, file)

.then(

function (data) {

alert("Uploaded successfully");

},

function (err) {

alert(JSON.stringify(err));

}

);

Conclusions

As with most things in programming, it’s pretty simple when someone shows you how. Sparse documentation on MSDN, however, gave me a couple of days of agony. (I'll probably get a laugh when a reader points me at a full code sample somehere on MSDN that I missed.)

The big takeaway from this effort is that now you can easily use the REST interface for file uploading, which is good for files up to 2GB. Because CSOM is limited to 1.5MB, it seems like there is really little point to using anything but REST.

Uploading Files in SharePoint 2013 using CSOM and REST的更多相关文章

  1. SharePoint 2013 开发——CSOM概要

    博客地址:http://blog.csdn.net/FoxDave 本篇对客户端API做一个大致地了解. 看一下各个类别主要API之间的对应关系表. 假设我们对Server API已经有了足够地了 ...

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

    http://techmikael.blogspot.in/2013/07/how-to-copy-files-between-sites-using.html I'm currently playi ...

  3. 解决SharePoint 2013 designer workflow 在发布的报错“负载平衡没有设置”The workflow files were saved but cannot be run.

    原因是app management service没有设置好,在管理中心把他删掉,重新建一个就可以了 Provision App Management Service In SharePoint 20 ...

  4. SharePoint 2013 开发——搜索架构及扩展

    博客地址:http://blog.csdn.net/FoxDave SharePoint 2013高度整合了搜索引擎,在一个场中只有一个搜索服务应用程序(SSA).它集成了FAST,只有一个代码库 ...

  5. SharePoint 2013的100个新功能之开发

    一:SharePoint应用 SharePoint 2013引入了云应用模型来供用户创建应用.SharePoint应用是独立的功能整合,扩展了SharePoint网站的功能.应用可以包含SharePo ...

  6. 实现一个基于 SharePoint 2013 的 Timecard 应用(中)

    门户视图 随着 Timecard 列表的增多,如何查找和管理这许多的 Timecard 也就成了问题.尤其对于团队经理而言,他除了自己填写的 Timecard,还要审核团队成员的 Timecard 任 ...

  7. 实现一个基于 SharePoint 2013 的 Timecard 应用(上)

    在 SharePoint 2013 上面实现一个 Timecard 应用的想法来自一个真实的需求,而实现的方案在我脑海里面盘旋已经很久了,终于这几天准备安排点儿时间将它实现出来. “ We start ...

  8. Integrating SharePoint 2013 with ADFS and Shibboleth

    Time again to attempt to implement that exciting technology, Federation Services (Web Single Sign On ...

  9. office 365 Sharepoint 2013

    平台环境: office 365 Sharepoint  2013 操作文件和文件夹 访问文档库的最佳方式是借助在 /_api/web 处可用的 GetFolderByServerRelativeUr ...

随机推荐

  1. Inkpad中文翻译已合并到官方项目

    今天 Steve Sprang 已合并了#100提交请求,Inkpad即将在AppStore上发布简体中文版了! 20天前因一个偶然原因启动翻译的: 当晚(周六)我想对iPad上的矢量绘图软件进行交互 ...

  2. MyBatis知多少(22)MyBatis删除操作

    本节从表中使用MyBatis删除记录. 我们已经在MySQL下有EMPLOYEE表: CREATE TABLE EMPLOYEE ( id INT NOT NULL auto_increment, f ...

  3. ServiceStack 介绍

    关于ServiceStack ServiceStack 官网介绍: Opensource .NET and Mono REST Web Services framework 什么是 ServiceSt ...

  4. 快乐的JS正则表达式(二)

    在上一篇中介绍了一个test方法,在本文中将使用另外一个,exec方法可以找到匹配的结果并且返回结果以及位置.exec("正则"): 简单测试: var str = "{ ...

  5. zoj 3261 Connections in Galaxy War

    点击打开链接zoj 3261 思路: 带权并查集 分析: 1 题目说的是有n个星球0~n-1,每个星球都有一个战斗值.n个星球之间有一些联系,并且n个星球之间会有互相伤害 2 根本没有思路的题,看了网 ...

  6. 在Eclipse中进行HotSpot的源码调试--转

    原文地址:http://www.linuxidc.com/Linux/2015-05/117250.htm 在阅读OpenJDK源码的过程中,经常需要运行.调试程序来帮助理解.我们现在已经可以编译出一 ...

  7. 另一个 OleDbParameterCollection 中已包含 OleDbParameter 错误分析及解决办法

    程序非常简单,就是从一个表中取出一个符合要求的数据,如果取到,就把该数据对应的计数加1.也就是执行不同的两个SQL语句操作同一个表,并且这两个SQL的参数是一样的.在一个函数里完成这个调用.执行第二个 ...

  8. [Tool] 常用开发工具注册码(持续更新)

    OS win10 激活 命令行 打开命令提示符( 管理员 ) 输入 slmgr /ipk W269N-WFGWX-YVC9B-4J6C9-T83GX 回车 再输入 slmgr /skms kms.xs ...

  9. 搜索 + 剪枝 --- POJ 1101 : Sticks

    Sticks Problem's Link:   http://poj.org/problem?id=1011 Mean: http://poj.org/problem?id=1011&lan ...

  10. C#设计模式——原型模式(Prototype Pattern)

    一.概述 在软件开发中,经常会碰上某些对象,其创建的过程比较复杂,而且随着需求的变化,其创建过程也会发生剧烈的变化,但他们的接口却能比较稳定.对这类对象的创建,我们应该遵循依赖倒置原则,即抽象不应该依 ...