I am trying to upload a file to a document library and keep getting a statusCode of 400 with the text just saying "Bad Request." I was rifling through some other forums and saw that the API could potentially not have the right permissions but I haven't been able to figure out how to even check that, let alone set it to have full control.
Additionally, the site where the document library lives is a subsite, so I'm not sure if that has an effect on what I'm trying to do but I haven't seen an example where the library lives in a subsite to know if it does affect anything.
Here is my code, site name removed for client privacy, (largely taken from this post):
function dofunc() {
var control = document.getElementById("elementIDHere");
control.addEventListener("change", fdocattach, false);
}
var file;
var contents;
function fdocattach(event) {
var i = 0,
files = event.srcElement.files,
len = files.length;
for (; i < len; i++) {
console.log("Filename: " + files[i].name);
console.log("Type: " + files[i].type);
console.log("Size: " + files[i].size + " bytes");
}
if (!window.FileReader) {
alert("The FileSystem APIs are not fully supported in this browser.");
return false;
}
if (files.length > 0) {
file = files[0];
fileName = file.name;
var reader = new FileReader();
reader.onload = fonload;
reader.onerror = function(event) {
console.error("File reading error " + event.target.error.code);
};
reader.readAsArrayBuffer(file);
}
return false;
}
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 binary;
}
function fonload(event) {
contents = event.target.result;
$.getScript("sitename/subsite/_layouts/15/SP.RequestExecutor.js", fonload2);
}
function fonload2() {
var contents2 = _arrayBufferToBase64(contents);
var createitem = new SP.RequestExecutor("sitename/subsite");
createitem.executeAsync({
url: "sitename/subsite/_api/web/GetFileByServerRelativeUrl('/documentLibraryName')/Files/add(url='" + file.name + "',overwrite=true)",
method: "POST",
binaryStringRequestBody: true,
body: contents2,
success: fsucc,
error: ferr
state: "Update"
});
function fsucc(data)
{
alert('success');
}
function ferr(data)
{
alert('error\n\n' + data.statusText + "\n\n" + data.responseText);
}
}