Monday, 4 August 2014

Uploading Files Using the REST API and Client Side Techniques


function AttachFile(file) {
var MyListName = "MyList";
var ItemId = "20";
fileRead(file).then(
function (buffer) {
var bytes = new Uint8Array(buffer);
var binary = '';
for (var b = 0; b < bytes.length; b++) {
binary += String.fromCharCode(bytes[b]);
}
var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
$.getScript(scriptbase + "SP.RequestExecutor.js", function () {
var createitem = new SP.RequestExecutor(_spPageContextInfo.webServerRelativeUrl);
createitem.executeAsync({
url: _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/GetByTitle('" + MyListName + "')/items(" + ItemId + ")/AttachmentFiles/add(FileName='" + file.name + "')",
method: "POST",
binaryStringRequestBody: true,
body: binary,
success: sucessM,
error: errorM,
state: "Update"
});
function sucessM(data) {
console.log('Done');
}
function errorM(data) {
console.log('error\n\n' + data.statusText + "\n\n" + data.responseText);
}
});
},
function (err) {
console.log('error\n\n' + err.statusText + "\n\n" + err.responseText);
}
);
}
function fileRead(file) {
var reader = new FileReader();
reader.onload = function (e) {
console.log(e.target.result);
}
reader.onerror = function (e) {
console.log(e.target.error);
}
reader.readAsArrayBuffer(file);
}
view raw gistfile1.js hosted with ❤ by GitHub