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与大家 ...
随机推荐
- 轻松自动化---selenium-webdriver(python) (十二)
本节重点: l 键盘按键用法 l 键盘组合键用法 l send_keys() 输入中文运行报错问题 键盘按键键用法: #coding=utf-8 from selenium import webdri ...
- 推荐10个 CSS3 制作的创意下拉菜单效果
下拉菜单是一个很常见的效果,在网站设计中被广泛使用.通过使用下拉菜单,设计者不仅可以在网站设计中营造出色的视觉吸引力,但也可以为网站提供了一个有效的导航方案.使用 HTML5 和 CSS3 可以更容易 ...
- mysql判断一条记录是否存在,如果存在,则更新此语句,如果不存在,则插入
前言,在我们的业务逻辑中,很有可能会遇到这样的情况. 1.我要更新一条记录的值. 2.但是我不确定这条记录存不存在??? 3.那如果存在?我就更新,如果不存在,我就插入! 那么如果这样,一般情况下,我 ...
- Elasticsearch入门必备——ES中的字段类型以及常用属性
使用Elasticsearch时,了解字段的概念,是必不可少的.毕竟无论是es还是传统的数据库,都无法弱化字段的类型. 背景知识 在Es中,字段的类型很关键: 在索引的时候,如果字段第一次出现,会自动 ...
- 解决SpringMVC的@ResponseBody返回中文乱码
SpringMVC的@ResponseBody返回中文乱码的原因是SpringMVC默认处理的字符集是ISO-8859-1,在Spring的org.springframework.http.conve ...
- 实现UniqueAttribute唯一性约束
using System; using System.ComponentModel.DataAnnotations; using System.Data.Entity; namespace Zwj.T ...
- C语言学习001:让程序跑起来
编译工具下载 MinGW - Minimalist GNU for Windows 编译运行 #include <stdio.h> int main(){ puts("C roc ...
- ASP.NET MVC部分视图PartialView的使用
在ASP.NET MVC项目中,部分视图PartialVieww使用很广.它实际就是在ASP.NET环境的用户自定义控件UserControl. 在控制器中,创建一个视图操作Action和一个部分视图 ...
- poj-2236-Wireless Network
Wireless Network Time Limit: 10000MS Memory Limit: 65536K Total Submissions: 24155 Accepted: 100 ...
- 高频sql语句汇总。不断更新。。
操作 语句 创建数据库 CREATE DATABASE dbname/* DEFAULT CHARSET utf8 COLLATE utf8_general_ci;*/ 删除数据库 DROP DATA ...