0

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)" > 
Dave Clark
  • 2,243
  • 15
  • 32
netzero
  • 73
  • 4
  • Check out this jsfiddle example, http://jsfiddle.net/qL86Z/8/ and this stackoverflow question https://stackoverflow.com/questions/14967647/encode-decode-image-with-base64-breaks-image – sissonb Jul 06 '17 at 20:40

1 Answers1

1

i figured it out, for anyone else having a similar issue. It turns out that you cant take the data outside the onload function, you have to pass the data out to another function using a callback function. See below.

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(eve){
    var theResult = reader.result;
    str = _arrayBufferToBase64(theResult);
    AttachFileFunction(file.name,file.type,str);
};
   
reader.readAsArrayBuffer(file);
  
Daryl
  • 18,592
  • 9
  • 78
  • 145
netzero
  • 73
  • 4