首页 > 代码库 > SharePoint上传文件
SharePoint上传文件
一、使用JS上传到Document
<%--html代码部分,使用konckout,记得要在页面上绑定--%>
<%--在本页绑定konockout--%>
var IBDModel = new Akmii.OTIS.China.Workflow.IBDModel();
ko.applyBindings(uploadModels.uploadModel );
<label class="ak-left ak-proplatform-rcontent-row-label" style="line-height: 25px;margin-right: 5px;">选择文件</label>
<input type="file" style="display: inline-block;" class="ak-left ak-proplatform-upload-input" id="DocList" data-bind="value: $root.Field_AttachmentName" />
<div class="ak-left ak-proplatform-attinfo-inline-upload" >
<a href="http://www.mamicode.com/#" data-bind="click: $root.UploadDocuments"><span class="ak-left">上传</span></a>
<%--上传部分的代码--%>
var FileUploadHelper = window.FileUploadHelper || {};
FileUploadHelper.Libs = function () {
/*//BosKat 2014-08-04 Mon Start add
Flag 是为文件名添加时间的参数
1 表示添加时间
否则,表示什么都不传送
*/
var upload = function (FileInfo, fileInput, serverRelativeUrl, flag) {
//alert("1");
var file = fileInput[0].files[0];
//alert(file.name);
//var serverRelativeUrl = "Lists/Documents";
//BosKat 2014-08-04 Mon Start modify
//为了保证Attachment 的filePath 和 Document 的Name相对应
//达到能够进行文档的重复上传工作,通过当前时间解决
if (flag == 1) {
var tmpFileName = file.name;
var extName = tmpFileName.substring(tmpFileName.lastIndexOf("."));
var fileName = tmpFileName.substring(0, tmpFileName.lastIndexOf("."));
var time = new Date().format("yyyy_MM_dd_hh_mm_ss").toString();
FileInfo.fileName = fileName + "_" + time + extName;
}
else {
FileInfo.fileName = file.name;
}
var fileName = encodeURI(file.name);
FileInfo.fileUrl = encodeURI("/" + serverRelativeUrl + "/" + fileName);
var deferred = $.Deferred();
getFileBuffer(file).then(function (arrayBuffer) {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl +
"/_api/web/GetFolderByServerRelativeUrl(‘" + serverRelativeUrl + "‘)/Files" +
"/Add(url=‘" + encodeURI(FileInfo.fileName)+ "‘, overwrite=true)",
type: "POST",
data: arrayBuffer,
processData: false,
headers: {
"accept": "application/json;odata=http://www.mamicode.com/verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-length": arrayBuffer.byteLength
},
success: function (data) {
deferred.resolve(data);
},
error: function (err) {
deferred.reject(err);
}
});
},
function (err) {
deferred.reject(err);
}
);
return deferred.promise();
},
getFileBuffer = function (file) {
var deferred = $.Deferred();
var reader = new FileReader();
reader.onload = function (e) {
deferred.resolve(e.target.result);
}
reader.onerror = function (e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(file);
return deferred.promise();
};
return {
upload: upload
};
}();
<%--调用上传代码--%>
(function (namespace) {
var uploadModel = function(){
//调用上传方法并返回一个data值
FileUploadHelper.Libs.upload(FileInfo, fileInput, "Shared Documents", 1).then(function (data) {}
}
})(uploadModels)
SharePoint上传文件