一、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. CSS3 过渡特性创建信封效果的联系表单

    最近给大家分享 CSS3 效果比较多,都是充分运用了 CSS3 来实现的.通过 CSS3 的新特性,我们创作出好的交互和效果的可能性大大增加.这篇文章中,我想与大家分享使用 CSS3 过渡特性实现的信 ...

  2. Chrome开发者工具详解(3)-Timeline面板

    Chrome开发者工具详解(3)-Timeline面板 注: 这一篇主要讲解面板Timeline,参考了Google的相关文档,主要用于公司内部技术分享.. Timeline面板 Timeline面板 ...

  3. EF基本操作增、删、查、改、分页,join……等

    一.批量添加数据 static void Main(string[] args) { add(); add2(); Console.ReadKey(); } static void add() { D ...

  4. Spring @Transactional propagation 各个属性值的含义

    REQUIRED:业务方法需要在一个容器里运行.如果方法运行时,已经处在一个事务中,那么加入到这个事务,否则自己新建一个新的事务. NOT_SUPPORTED:声明方法不需要事务.如果方法没有关联到一 ...

  5. C#串口通信—向串口发送数据,同步接收返回数据

    最近写C#串口通信程序,系统是B/S架构.SerialPort类有一个DataReceived事件,用来接收串口返回的数据,但这种方式在C/S架构下很好用,但B/S就不好处理了.所以写了一个同步模式接 ...

  6. ASP.NET MVC图片管理(更新)

    Insus.NET在ASP.NET MVC专案中,实现了图片管理,上传,预览,显示,删除等功能,还差一个功能,就是更新图片的功能,那这次来完成它.你可以先参考前2篇<ASP.NET MVC图片管 ...

  7. 帝国cmsV6.6版数据表

    信息表:每个模型都有以下六个表 phome_ecms_news 新闻系统模型-主表 phome_ecms_news_data_1 新闻系统模型-副表1 副表可无限增加 信息表 phome_ecms_n ...

  8. 一些C#实用的方法汇总

    代码如下: /// <summary> /// 过滤字符串方法,用于将单引号等特殊符号转化成中文符号 /// </summary> /// <param name=&qu ...

  9. 疯狂Android讲义 - 学习笔记(一)

    常用开发工具的用法 android : 启动Android SDK管理器 android --help  查看具体用法 android create avd -n t10 -t 10 -b armea ...

  10. java 四舍五入保留小数

    // 方式一: double f = 3.1516; BigDecimal b = new BigDecimal(f); double f1 = b.setScale(2, BigDecimal.RO ...