一、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. weback学习笔记

    weback可以把各种资源,例如JS(含JSX).coffee.样式(含less/sass).图片等都作为模块来使用和处理.同时支持amd cmd CommonJS语法.同时可以和gulp一块使用. ...

  2. PHP类和对象函数实例详解

    1. interface_exists.class_exists.method_exists和property_exists: 顾名思义,从以上几个函数的命名便可以猜出几分他们的功能.我想这也是我随着 ...

  3. 使用etcd+confd管理nginx配置

    1.前言 最近在项目中用nginx做反向代理,需要动态生成nginx的配置.大概流程是用户在页面上新增域名.http或https协议以及端口信息,后台会根据域名自动生成一个nginx的server配置 ...

  4. Spark RDD到底是个什么东西

    前言 用Spark有一段时间了,但是感觉还是停留在表面,对于Spark的RDD的理解还是停留在概念上,即只知道它是个弹性分布式数据集,其他的一概不知 有点略显惭愧.下面记录下我对RDD的新的理解. 官 ...

  5. ASP.NET Core WebAPI 开发-新建WebAPI项目

    ASP.NET Core WebAPI 开发-新建WebAPI项目, ASP.NET Core 1.0 RC2 即将发布,我们现在来学习一下 ASP.NET Core WebAPI开发. 网上已经有泄 ...

  6. datatable删除行

    先列出正确的写法,如果你只想马上改错就先复制吧, protected void deleteDataRow(int RowID,DataTable dt) { ; i >= ; i--) { i ...

  7. 背水一战 Windows 10 (8) - 控件 UI: StateTrigger

    [源码下载] 背水一战 Windows 10 (8) - 控件 UI: StateTrigger 作者:webabcd 介绍背水一战 Windows 10 之 控件 UI VisualState 之 ...

  8. jquery基本选择器匹配多个元素

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  9. 传智播客JavaWeb听课总结

    一. JavaWeb基础 第一天: 1.Eclipse详解: (1).Bad versionnumber in .class file:编译器版本和运行(JRE)版本不符合.高的JRE版本兼容低版本的 ...

  10. Statement和PreparedStatement的区别; 什么是SQL注入,怎么防止SQL注入?

    问题一:Statement和PreparedStatement的区别 先来说说,什么是java中的Statement:Statement是java执行数据库操作的一个重要方法,用于在已经建立数据库连接 ...