一、HTML控件

    <input type="file" id="upFile" style="width:300px;"/>
<div id="fileDisplayArea">
</div>
<input type="button" value="Upload" onclick="CreateFile()" />

二、FileCreationInformation 方式

        var file;
var newFile;
var fileCreateInfo;
function CreateFile() {
// Ensure the HTML5 FileReader API is supported
if (window.FileReader) {
input = document.getElementById("upFile");
if (input) {
file = input.files[0];
fr = new FileReader();
fr.onload = receivedBinary;
fr.readAsDataURL(file);
}
}
else {
alert("The HTML5 FileSystem APIs are not fully supported in this browser.");
}
} // Callback function for onload event of FileReader
function receivedBinary() { var clientContext = new SP.ClientContext.get_current();
var oWebsite = clientContext.get_web();
clientContext.load(oWebsite);
var list = oWebsite.get_lists().getByTitle("Apptexfiles"); fileCreateInfo = new SP.FileCreationInformation();
fileCreateInfo.set_url(file.name);
fileCreateInfo.set_overwrite(true);
fileCreateInfo.set_content(new SP.Base64EncodedByteArray()); // Read the binary contents of the base 64 data URL into a Uint8Array
// Append the contents of this array to the SP.FileCreationInformation
var arr = convertDataURIToBinary(this.result);
for (var i = 0; i < arr.length; ++i) {
fileCreateInfo.get_content().append(arr[i]);
} // Upload the file to the root folder of the document library
newFile = list.get_rootFolder().get_files().add(fileCreateInfo); clientContext.load(newFile, 'ListItemAllFields'); //'Include(ID, Title, FileRef)'
clientContext.executeQueryAsync(onSuccess, onFailure);
} function onSuccess() {
// File successfully uploaded
alert("Success!");
} function onFailure() {
// Error occurred
alert("Request failed: " + arguments[1].get_message());
console.log("Request failed: " + arguments[1].get_message());
} // Utility function to remove base64 URL prefix and store base64-encoded string in a Uint8Array
// Courtesy: https://gist.github.com/borismus/1032746
function convertDataURIToBinary(dataURI) {
var BASE64_MARKER = ';base64,';
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength)); for (i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}

三、SOAP 方式

        function ShowMailDialog() {
var file = document.getElementById('upFile').files[0];
if (file) {
UploadFile(file);
}
}
function UploadFile(readFile) {
var reader = new FileReader();
reader.readAsArrayBuffer(readFile); //array buffer
reader.onprogress = updateProgress;
reader.onload = loaded;
reader.onerror = errorHandler;
}
function loaded(evt) {
var fileString = evt.target.result;
var X = _arrayBufferToBase64(fileString); // this is the mothod to convert Buffer array to Binary
var fileInput = document.getElementById('upFile');
var fileDisplayArea = document.getElementById('fileDisplayArea');
var file = fileInput.values;
var filePath = $('#upFile').val(); // "c:\\test.pdf";
var file = filePath.match(/\\([^\\]+)$/)[1]; var soapEnv =
"<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'> \
<soap:Body>\
<CopyIntoItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>\
<SourceUrl>" + filePath + "</SourceUrl>\
<DestinationUrls>\
<string>https://nike.sharepoint.com/teams/ap1/gctech/DEV/Apptexfiles/" + file + "</string>\
</DestinationUrls>\
<Fields>\
<FieldInformation Type='Text' DisplayName='Title' InternalName='Title' Value='Test' />\
<FieldInformation Type='Text' DisplayName='BudgetId' InternalName='BudgetId' Value='8' />\
</Fields>\
<Stream>" + X + "</Stream>\
</CopyIntoItems>\
</soap:Body>\
</soap:Envelope>"; $.ajax({
url: "https://nike.sharepoint.com/teams/ap1/gctech/DEV/_vti_bin/copy.asmx",
beforeSend: function (xhr) { xhr.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/CopyIntoItems"); },
type: "POST",
dataType: "xml",
data: soapEnv,
complete: processResult,
contentType: "text/xml; charset=\"utf-8\""
}); }
//SP.SOD.executeOrDelayUntilScriptLoaded(initialize, 'SP.js');
//SP.SOD.executeOrDelayUntilScriptLoaded(test, 'SP.js'); function errorHandler(evt) {
if (evt.target.error.name == "NotReadableError") {
// The file could not be read.
}
}
function _arrayBufferToBase64(buffer) {
var binary = ''
var bytes = new Uint8Array(buffer)
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i])
}
return window.btoa(binary);
}
function updateProgress(evt) {
}
function processResult(xData, status) {
alert("Uploaded SuccessFully");
}

四、创建Item及上传附件

//Create other item with an attachment.
function CreateOtherItem()
{
var otherlist = curWeb.get_lists().getByTitle(otherListTitle);
var itemCreateInfo = new SP.ListItemCreationInformation();
var otherItem = otherlist.addItem(itemCreateInfo); otherItem.set_item("Title", $("#txtReqName").val().trim()); otherItem.update();
curContext.load(otherItem); //, 'Include(ID, Title)'
curContext.executeQueryAsync(Function.createDelegate(this, onCreateSucceeded), Function.createDelegate(this, onCreateFailed));
function onCreateSucceeded(sender, args) {
var itemId = otherItem.get_item("ID");
var rootUrl = otherItem.get_item('FileDirRef');
var attachFolder; if (!otherItem.get_item('Attachments')) { //Create new folder
var rootAttachUrl = String.format('{0}/Attachments', rootUrl); //list.get_rootFolder().get_serverRelativeUrl()
var rootAttachFolder = curWeb.getFolderByServerRelativeUrl(rootAttachUrl);
attachFolder = rootAttachFolder.get_folders().add("_" + itemId);
attachFolder.moveTo(rootAttachUrl + '/' + itemId);
curContext.load(attachFolder);
}
else {
var attachFolderUrl = String.format('{0}/Attachments/{1}', rootUrl, itemId);
attachFolder = curWeb.getFolderByServerRelativeUrl(attachFolderUrl);
curContext.load(attachFolder);
}
curContext.executeQueryAsync(onSuccess, onFailure); function onSuccess() {
var newFile;
var fileCreateInfo;
var input = document.getElementById("upApproval");
var file = input.files[0];
var freader = new FileReader();
freader.onload = function (e) {
fileCreateInfo = new SP.FileCreationInformation();
fileCreateInfo.set_url(file.name);
fileCreateInfo.set_overwrite(true); var encContent = new SP.Base64EncodedByteArray();
var arr = convertDataURIToBinary(e.target.result);
for (var i = 0; i < arr.length; ++i) {
encContent.append(arr[i]);
}
fileCreateInfo.set_content(encContent); newFile = attachFolder.get_files().add(fileCreateInfo);
curContext.load(newFile);
curContext.executeQueryAsync();
alert("Success!");
};
freader.readAsDataURL(file);
}
function onFailure() {
// Error occurred
alert("Request failed: " + arguments[1].get_message());
console.log("Request failed: " + arguments[1].get_message());
}
}
function onCreateFailed(sender, args) {
console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
}

SPS中JSOM和SOAP 实现文件上传的更多相关文章

  1. JavaEE开发之SpringMVC中的自定义消息转换器与文件上传

    上篇博客我们详细的聊了<JavaEE开发之SpringMVC中的静态资源映射及服务器推送技术>,本篇博客依然是JavaEE开发中的内容,我们就来聊一下SpringMVC中的自定义消息转发器 ...

  2. 在 .NET Core项目中使用UEditor图片、文件上传服务

    在.NET Framework中使用UEditor时,只需要将UEditor提供的后端服务,部署为一个子程序,即可直接使用文件上传相关的服务,但是UEditor官方并未提供.Net Core的项目,并 ...

  3. 在express项目中使用formidable & multiparty实现文件上传

    安装 formidable,multiparty 模块 npm install formidable,multiparty –save -d 表单上传 <form id="addFor ...

  4. springBoot中使用使用junit测试文件上传,以及文件下载接口编写

    本篇文章将介绍如何使junit在springBoot中测试文件的上传,首先先阅读如何在springBoot中进行接口测试. 文件上传操作测试代码 import org.junit.Before; im ...

  5. Java中request请求之 - 带文件上传的form表单

    常用系统开发中总免不了显示图片,保存一些文件资料等操作. 这些操作的背后,就是程序员最熟悉的 enctype="multipart/form-data"类型的表单. 说起file类 ...

  6. 在ASP.NET中实现图片、视频文件上传方式

    一.图片 1.在前端用<asp:FileUpload ID="UpImgName" runat="server"/>控件 2.在后台.cs中写上 p ...

  7. Java中简单测试FastDFS的文件上传

    pom.xml文件内容如下: <dependencies> <!-- fastdfs --> <dependency> <groupId>org.cso ...

  8. [Asp.net]通过uploadify将文件上传到B服务器的共享文件夹中

    写在前面 客户有这样的一个需求,针对项目中文档共享的模块,客户提出如果用户上传特别的大,或者时间久了硬盘空间就会吃满,能不能将这些文件上传到其他的服务器?然后就稍微研究了下这方面的东西,上传到网络中的 ...

  9. jsp\struts1.2\struts2 中文件上传(转)

    jsp\struts1.2\struts2 中文件上传 a.在jsp中简单利用Commons-fileupload组件实现 b.在struts1.2中实现c.在sturts2中实现现在把Code与大家 ...

随机推荐

  1. 【特别推荐】Web 开发人员必备的经典 HTML5 教程

    对于我来说,Web 前端开发是最酷的职业之一,因为你可以用新的技术发挥,创造出一些惊人的东西.唯一的问题是,你需要跟上这个领域的发展脚步,因此,你必须不断的学习,不断的前进.本文将分享能够帮助您快速掌 ...

  2. 你真的精通 CSS 了?来挑战一下 CSS 选择器测验吧

    CSS 选择器赋予 CSS 强大的 HTML 元素匹配功能.作为前端开发人员必须要掌握的一部分,可能基本的大家都知道.但是你真的精通 CSS 了吗?挑战一下 CSS 选择器测验就知道. 您可能感兴趣的 ...

  3. Tridiv:基于 Web 的 CSS 编辑器,创建炫丽 3D 图形

    Tridiv 是一个基于 Web 的编辑器,使用 CSS 创建 3D 形状.它提供了一个传统的四个面板的操作界面,给出了从每个平面的视图,以及一个预览窗格中示出的最终的效果.使用 Tridiv 可以创 ...

  4. Windows Azure Service Bus (1) 基础

    <Windows Azure Platform 系列文章目录> 我们在基于Windows Azure进行云端开发的时候,云端的软件通常都需要与其他软件进行交互.这些其他软件可能包括其他In ...

  5. express 框架之session

    一.什么是session? 最近在学习node.js 的express框架,接触到了关于session方面的内容.翻阅了一些的博客,学到了不少东西,发现一篇博文讲的很好,概念内容摘抄如下: Sessi ...

  6. 在IBM Bluemix上部署Hyperledger应用

    简介 IBM Bluemix (http://www.ibm.com/bluemix‎)是一个基于cloud的应用开发和部署平台,提供包括多种服务和运行环境的支持.对Hyperledger应用开发者而 ...

  7. 运用javascript的成员访问特性来实现通用版的兼容所有浏览器的打开对话框功能

    打开网页对话框,一般有三种方法:window.open.window.showModalDialog.window.showModelessDialog,每一种都有它的优点与不足.第一种方法:wind ...

  8. [Tool] 配置文件之Web.config

    开发人员工具: 安装完vs后,(如2013:C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\Shortcuts\VS ...

  9. Maven提高篇系列之(五)——处理依赖冲突

    这是一个Maven提高篇的系列,包含有以下文章: Maven提高篇系列之(一)——多模块 vs 继承 Maven提高篇系列之(二)——配置Plugin到某个Phase(以Selenium集成测试为例) ...

  10. JavaScript基础插曲-练习

    Javascript基础学习 eg:利用正则表达式来去掉空格. 1:msg=' Hello ': <script type="text/javascript">     ...