我目前正在开发一个页面,用户可以从本地计算机文件上传到sharepoint 2013服务器。
目前我已经设法试验了ajax调用并使用其余的api来创建简单的.txt文件和其他文件夹。
我遇到的问题是我在尝试上传.doc文件或使用arrayBuffer作为数据的任何其他文件时得到的响应。
这是我的代码(再次工作的是传递的数据是一个简单的字符串:
url = "http://temp-sharepoint/_api/Web/GetFolderByServerRelativeUrl('Documents')/files/add(overwrite=true,url='"+fileName+"')";
jQuery.ajax({
url: url,
type: "POST",
data: arrayBuffer,
processData: false,
headers: {
"Accept": "application/json; odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
"content-length": arrayBuffer.byteLength
},
success: doSuccess,
error: onError
});
上面的代码会产生
的回复[对象错误] {描述:"参数...",消息:"参数...",名称:"错误" ,编号:-2147024809,堆栈:"错误:......"}
是"参数不正确。"
再次,如果数据是"测试"正在创建文件没有问题。
我对sharepoint很新,如果有人能指出我可能的解决方案,我将不胜感激。
感谢。
答案 0 :(得分:0)
如果在使用浏览器调试器调试时包含正确的数据,您如何将文件读入缓冲区检查
上传文件的示例代码
function uploadDocument(buffer, fileName) {
var url = String.format(
"{0}/_api/Web/Lists/getByTitle('Project Documents')/RootFolder/Files/Add(url='{1}', overwrite=true)",
_spPageContextInfo.webAbsoluteUrl, fileName);
var call = jQuery.ajax({
url: url,
type: "POST",
data: buffer,
processData: false,
headers: {
Accept: "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
"Content-Length": buffer.byteLength
}
});
}
答案 1 :(得分:0)
如果你想上传很多,而你正在使用nintex(非常类似于jquery)
NWF$("#getFile").on('change', function () {
var files = this.files;
for (var i = 0; i < files.length; i++) {
// IFFY to save the current index
(function (x) {
var file = files[x];
lastFileName = file.name;
var fileName = Date.now() + file.name;
var getFileBuffer = function (file) {
//alert('in getFileBuffer');
var deferred = NWF$.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();
};
getFileBuffer(file).then(function (buffer) {
//alert(buffer);
NWF$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items(1)/AttachmentFiles/add(FileName='" + fileName + "')",
method: 'POST',
body: "Contents of file",
data: buffer,
processData: false,
headers: {
"ACCEPT": "application/json; odata=verbose",
"content-type": "application/json; odata=verbose",
"X-RequestDigest": document.getElementById("__REQUESTDIGEST").value
// "content-length": buffer.byteLength
}, //end headers
success: function (data) {
++indexFile;
console.log(data);
var fileUrl = _spPageContextInfo.siteAbsoluteUrl + data.d.ServerRelativeUrl;
NWF$('#displayFiles tr:last').after('<tr><td><a class="fileLink" href="' + fileUrl + '">' + lastFileName + '</a></td><td><a class="removeHyper">מחיקה ×</a></td></tr>');
filesItems.push(_spPageContextInfo.siteAbsoluteUrl + data.d.ServerRelativeUrl);
NWF$('#' + filesList).text(converAddressToString(filesItems))
},
error: function (data) {
console.log("err " + data.d);
}
});
})
})(i)
答案 2 :(得分:0)
//Try using this if you need to upload multiple items too with file type and size restrictions.
var appWebUrl, hostWebUrl;
jquery(document).ready(function () {
// Check for FileReader API (HTML5) support.
if (!window.FileReader) {
alert('This browser does not support the FileReader API.');
}
// Get the add-in web and host web URLs.
appWebUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
hostWebUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
});
// Upload the file.
// You can upload files up to 2 GB with the REST API.
function uploadFile() {
// Define the folder path for this example.
var serverRelativeUrlToFolder = '/shared documents';
// Get test values from the file input and text input page controls.
// The display name must be unique every time you run the example.
var fileInput = jQuery('#getFile');
var newName = jQuery('#displayName').val();
// Initiate method calls using jQuery promises.
// Get the local file as an array buffer.
var getFile = getFileBuffer();
getFile.done(function (arrayBuffer) {
// Add the file to the SharePoint folder.
var addFile = addFileToFolder(arrayBuffer);
addFile.done(function (file, status, xhr) {
// Get the list item that corresponds to the uploaded file.
var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
getItem.done(function (listItem, status, xhr) {
// Change the display name and title of the list item.
var changeItem = updateListItem(listItem.d.__metadata);
changeItem.done(function (data, status, xhr) {
alert('file uploaded and updated');
});
changeItem.fail(onError);
});
getItem.fail(onError);
});
addFile.fail(onError);
});
getFile.fail(onError);
// Get the local file as an array buffer.
function getFileBuffer() {
var deferred = jQuery.Deferred();
var reader = new FileReader();
reader.onloadend = function (e) {
deferred.resolve(e.target.result);
}
reader.onerror = function (e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(fileInput[0].files[0]);
return deferred.promise();
}
// Add the file to the file collection in the Shared Documents folder.
function addFileToFolder(arrayBuffer) {
// Get the file name from the file input control on the page.
var parts = fileInput[0].value.split('\\');
var fileName = parts[parts.length - 1];
// Construct the endpoint.
var fileCollectionEndpoint = String.format(
"{0}/_api/sp.appcontextsite(@target)/web/getfolderbyserverrelativeurl('{1}')/files" +
"/add(overwrite=true, url='{2}')?@target='{3}'",
appWebUrl, serverRelativeUrlToFolder, fileName, hostWebUrl);
// Send the request and return the response.
// This call returns the SharePoint file.
return jQuery.ajax({
url: fileCollectionEndpoint,
type: "POST",
data: arrayBuffer,
processData: false,
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
"content-length": arrayBuffer.byteLength
}
});
}
// Get the list item that corresponds to the file by calling the file's ListItemAllFields property.
function getListItem(fileListItemUri) {
// Construct the endpoint.
// The list item URI uses the host web, but the cross-domain call is sent to the
// add-in web and specifies the host web as the context site.
fileListItemUri = fileListItemUri.replace(hostWebUrl, '{0}');
fileListItemUri = fileListItemUri.replace('_api/Web', '_api/sp.appcontextsite(@target)/web');
var listItemAllFieldsEndpoint = String.format(fileListItemUri + "?@target='{1}'",
appWebUrl, hostWebUrl);
// Send the request and return the response.
return jQuery.ajax({
url: listItemAllFieldsEndpoint,
type: "GET",
headers: { "accept": "application/json;odata=verbose" }
});
}
// Change the display name and title of the list item.
function updateListItem(itemMetadata) {
// Construct the endpoint.
// Specify the host web as the context site.
var listItemUri = itemMetadata.uri.replace('_api/Web', '_api/sp.appcontextsite(@target)/web');
var listItemEndpoint = String.format(listItemUri + "?@target='{0}'", hostWebUrl);
// Define the list item changes. Use the FileLeafRef property to change the display name.
// For simplicity, also use the name as the title.
// The example gets the list item type from the item's metadata, but you can also get it from the
// ListItemEntityTypeFullName property of the list.
var body = String.format("{{'__metadata':{{'type':'{0}'}},'FileLeafRef':'{1}','Title':'{2}'}}",
itemMetadata.type, newName, newName);
// Send the request and return the promise.
// This call does not return response content from the server.
return jQuery.ajax({
url: listItemEndpoint,
type: "POST",
data: body,
headers: {
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
"content-type": "application/json;odata=verbose",
"content-length": body.length,
"IF-MATCH": itemMetadata.etag,
"X-HTTP-Method": "MERGE"
}
});
}
}
// Display error messages.
function onError(error) {
alert(error.responseText);
}
// Get parameters from the query string.
// For production purposes you may want to use a library to handle the query string.
function getQueryStringParameter(paramToRetrieve) {
var params = document.URL.split("?")[1].split("&");
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve) return singleParam[1];
}
}