I am using the following REST code to add a file as an attachment to a SharePoint 2013 list item.
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
<SharePoint:ScriptLink language="javascript" name="~site/Scripts/js/jquery-1.8.2.js" OnDemand="false" runat="server" Localizable="false"/>
<input id="ufile" type="file" ></input>
<script type="text/javascript">
$(document).ready(
doFunc()
);
function doFunc() {
var control = document.getElementById("ufile");
control.addEventListener("change", doAttach, false);
}
var fileName;
function doAttach(event) {
var files = event.srcElement.files;
if (!window.FileReader) {
alert("The FileSystem APIs are not fully supported in this browser.");
return false;
}
if (files.length > 0) {
var file = files[0];
fileName = file.name;
var reader = new FileReader();
reader.onload = onLoad;
reader.onerror = function(event) {
console.error("File reading error " + event.target.error.code);
};
reader.readAsDataURL(file);
}//
return false;
}
function onLoad(event) {
var contents = event.target.result;
$.ajax({
url: "/Test1/_api/web/lists/GetByTitle('List1')/items(1)/AttachmentFiles/add(FileName='" + fileName + "')",
type: "POST",
contentType: "application/octet-stream;odata=verbose",
data: contents,
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data)
{
alert("success");
},
error: function (data)
{
alert('error' + data.status + ':' + data.statusText + '\n' + data.responseText);
}
});
}
</script>
</asp:Content>
The file is uploaded, but contains "incorrect" data.
For example a jpeg file begins as follows: data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/...
Does anybody know whether the SharePoint 2013 REST API allows uploading non-text files correctly?