Html代码:
<html>
<input id="uploadFile" type="file">
<input type="button" onclick="AddAttachments(1)" value="Add Attachments">
</html>
在下面的javascript代码中,我尝试将附件添加到sharepoint list.But 得到错误如下: POST http://siteurl/_api/web/lists/getbytitle(&#39; DocUploadTest&#39;)/ items(1)/ AttachmentFiles / add(FileName =&#39; Test.txt&#39;)403(FORBIDDEN)
<script src="http://siteName/SiteAssets/ScriptFiles/jquery.min.js"></script>
<script type="text/javascript">
function AddAttachments(itemId)
{
var digest = "";
$.ajax(
{
url: "/_api/contextinfo",
method: "POST",
headers: {
"ACCEPT": "application/json;odata=verbose",
"content-type":
"application/json;odata=verbose"
},
success: function (data) {
digest = data.d.GetContextWebInformation.FormDigestValue;
},
error: function (data) {
}
}).done(function() {
var fileInput = $('#uploadFile');
var fileName = fileInput[0].files[0].name;
var reader = new FileReader();
reader.onload = function (e) {
var fileData = e.target.result;
var res11 = $.ajax(
{
url: "/_api/web/lists/getbytitle('DocUploadTest')/items("+itemId+")/AttachmentFiles/add(FileName='" + fileName + "')",
method: "POST",
binaryStringRequestBody: true,
data: fileData,
processData: false,
headers: {
"ACCEPT": "application/json;odata=verbose",
"X-RequestDigest": document.getElementById("__REQUESTDIGEST").value,
// "content-length": fileData.byteLength
},
success: function (data) {
console.log("success");
},
error: function (data) {
console.log("Error occured." + data.responseText);
}
});
};
reader.readAsArrayBuffer(fileInput[0].files[0]);
});
}
</script>
有人可以说出问题是什么吗?
答案 0 :(得分:0)
使用以下脚本为列表项添加附件:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var ID = 1;
var listname = "UploadTEST";
$("#my-attachments").change(function() {
var file = $(this)[0].files[0];
var 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();
};
getFileBuffer(file).then(function(buffer) {
console.log(buffer);
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl +
"/_api/web/lists/getbytitle('" + listname + "')/items(" + ID + ")/AttachmentFiles/add(FileName='" + file.name + "')",
method: 'POST',
data: buffer,
processData: false,
headers: {
"Accept": "application/json; odata=verbose",
"content-type": "application/json; odata=verbose",
"X-RequestDigest": document.getElementById("__REQUESTDIGEST").value
}
});
});
});
});
</script>
<input id="my-attachments" type="file"/>