SPS中JSOM和SOAP 实现文件上传
一、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 实现文件上传的更多相关文章
- JavaEE开发之SpringMVC中的自定义消息转换器与文件上传
上篇博客我们详细的聊了<JavaEE开发之SpringMVC中的静态资源映射及服务器推送技术>,本篇博客依然是JavaEE开发中的内容,我们就来聊一下SpringMVC中的自定义消息转发器 ...
- 在 .NET Core项目中使用UEditor图片、文件上传服务
在.NET Framework中使用UEditor时,只需要将UEditor提供的后端服务,部署为一个子程序,即可直接使用文件上传相关的服务,但是UEditor官方并未提供.Net Core的项目,并 ...
- 在express项目中使用formidable & multiparty实现文件上传
安装 formidable,multiparty 模块 npm install formidable,multiparty –save -d 表单上传 <form id="addFor ...
- springBoot中使用使用junit测试文件上传,以及文件下载接口编写
本篇文章将介绍如何使junit在springBoot中测试文件的上传,首先先阅读如何在springBoot中进行接口测试. 文件上传操作测试代码 import org.junit.Before; im ...
- Java中request请求之 - 带文件上传的form表单
常用系统开发中总免不了显示图片,保存一些文件资料等操作. 这些操作的背后,就是程序员最熟悉的 enctype="multipart/form-data"类型的表单. 说起file类 ...
- 在ASP.NET中实现图片、视频文件上传方式
一.图片 1.在前端用<asp:FileUpload ID="UpImgName" runat="server"/>控件 2.在后台.cs中写上 p ...
- Java中简单测试FastDFS的文件上传
pom.xml文件内容如下: <dependencies> <!-- fastdfs --> <dependency> <groupId>org.cso ...
- [Asp.net]通过uploadify将文件上传到B服务器的共享文件夹中
写在前面 客户有这样的一个需求,针对项目中文档共享的模块,客户提出如果用户上传特别的大,或者时间久了硬盘空间就会吃满,能不能将这些文件上传到其他的服务器?然后就稍微研究了下这方面的东西,上传到网络中的 ...
- jsp\struts1.2\struts2 中文件上传(转)
jsp\struts1.2\struts2 中文件上传 a.在jsp中简单利用Commons-fileupload组件实现 b.在struts1.2中实现c.在sturts2中实现现在把Code与大家 ...
随机推荐
- SQL Server存储(7/8) :理解BCM页
今天我们来讨论下批量更改映射(Bulk Changed Map:BCM)页,还有大容量日志恢复模式( bulk logged recovery model )如何运作的. 批量更改映射(Bulk Ch ...
- 基于HTML5的WebGL电信网管3D机房监控应用
先上段视频,不是在玩游戏哦,是规规矩矩的电信网管企业应用,嗯,全键盘的漫游3D机房: http://www.hightopo.com/guide/guide/core/3d/examples/exam ...
- SQL--工作中遇到的
--递归查询产品分类 WITH cte AS ( SELECT * FROM syn_Categories WHERE id = $CategoryID$ UNION ALL SELECT syn_C ...
- Auto Mapper01
在项目中一直在使用Auto Mapper技术,但是只是会简单的使用,对其里面的一些具体的细节和知识点不是很清楚,现在就跟着我从最基础的知识点来重新认识下,AutoMapper技术吧. ...
- git clone 失败问题解决方案
第一次从github上通过终端pull项目,出现了上述问题.询问了后台,才知道原来是电脑公钥(publickey)未添加至github,所以无法识别. 因而需要获取本地电脑公钥,然后登录github账 ...
- 原生JS 获取浏览器、窗口、元素等尺寸的方法及注意事项
一.通过浏览器获得屏幕的尺寸 screen.width screen.height screen.availHeight //获取去除状态栏后的屏幕高度 screen.availWidth //获取去 ...
- 设置与获取Cookie
自己编写的一个Cookie设置与获取函数,大家有什么感觉需要改进的地方,请告知与我,我一定虚心接受. JavaScript - Code: function setCookie(name,value, ...
- 控制器描述者(ControllerDescriptor),行为方法描述者(ActionDescriptor),参数描述者(ParameterDescriptor)的小结
Model的绑定是在Action方法绑定参数时发生的,这个绑定的参数过程要用到的元数据来自于控制器,行为方法和参数的描述者ContrllerDescriptor,ActionDescriptor和Pa ...
- Asp.Net WebForm和MVC同样优秀!
不是说MVC不好,而是WebForm并没有那么不堪,和Mvc同样优秀.对说WebForm缺点多的,表示不服,求指教,虽然本人有些见解可能比较浅薄. 看过很多文章和书籍,都会拿MVC模式和WebForm ...
- linq查询xml
1.加载xml字符串 XElement root = XElement.Parse(@"<?xml version='1.0' encoding='utf-8'?> <It ...