I am trying to make a java script web resource for dynamics CRM that essentially lets a user chose a file to upload and then stores it onto the annotation entity. I know the general procedure to do this however it keeps uploading empty files. The data is not getting converted to base 64 using the base 64 function. I am having a hard time using the File reader function to convert the file uploaded into base 64. The dataURL variable keeps returning empty. Can someone help me convert the chosen file to base 64? this does not have to be dynamics specific I think its a general java script html problem. I think i am using the File reader function wrong.
Thank you
function uploadFile(event) {
var input = event.target;
var file = input.files[0];
//var file = document.getElementById("myFile").files[0];
var str;
var reader = new FileReader();
reader.onload = function() {
var dataURL = reader.result;
str = _arrayBufferToBase64(dataURL);
};
reader.readAsDataURL(input.files[0]);
var id = window.parent.Xrm.Page.data.entity.getId();
var nam = window.parent.Xrm.Page.data.entity.getEntityName();
var entity = {};
entity.Subject = "first new annotation3";
entity.NoteText = "way to go you just made a new annotation";
entity.DocumentBody = str;
entity.FileName = file.name;
entity.MimeType = file.type;
entity.ObjectId = {
Id: id,
LogicalName: nam
};
SDK.REST.createRecord(entity, "Annotation", SucessCallback2, errorCallback2);
}
function _arrayBufferToBase64(buffer) { // Convert Array Buffer to Base 64 string
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
<
input type = "file"
id = "myFile"
placeholder = "Choose File"
onchange = "uploadFile(event)" >