Monday, 10 March 2014

Upload files to SharePoint list items


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function () {
$("#btnSubmit").click(function () {
var attach = $("#attachFile").val().split("\\");
var filename = attach[attach.length - 1];
var file = $("#attachFile")[0].files[0];
var id = "1";//Change this dynamically
AttachFile(objList, id, filename, file);
});
});
function AttachFile(objList, id, file) {
//var MyListName = "MyList";
//var ItemId = "20";
var MyListName = objList;
var ItemId = id;
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);
}
</script>
</head>
<body>
<input id="attachFile" type="file" />
<button id="btnSubmit">Submit</button>
</body>
</html>
view raw gistfile1.html hosted with ❤ by GitHub