Download Note Attachment using JavaScript and REST

In an earlier post we covered how to upload note attachment using JavaScript and REST. In this blog post we will learn how to download the note attachment using JavaScript and REST.

We have made a custom grid for displaying notes in the Microsoft Dynamics CRM as shown in the screenshot below.

Custom grid for displaying notes

Whenever some one clicks on the file name we want it to be downloaded in the browser.
We will make use of a popular open source file saver by Eli Grey for downloading purposes. So first of all download this FileSaver.js and upload it as a web resource to a solution of Dynamics CRM.

Now since we are using a custom grid for displaying notes and its attachments, we have made a hyperlink to the file name and called getFile(guid) custom method from it as shown below.
Note: The guid here is id of the selected or clicked record.You can modify this according to your scenario.


<a href=# onclick="getFile('+guid+')">
</a>

In getFile(guid) we are retrieving the attachment contents through REST as below


function getFile(guid){
SDK.REST.retrieveRecord(
guid,
"Annotation",
"DocumentBody,FileName",
'entitlement_Annotations',
function (result) {
var DocumentBody = result.DocumentBody;
var FileName = result.FileName;
dataURItoBlob(DocumentBody,FileName);
},
function (error) {
alert(error.message);
}
);
}

The dataURItoBlob() on line number 10 converts the retrieved contents to a Blob object as shown below.


function dataURItoBlob(dataURI,filename) {
// convert base64 to raw binary data held in a string
var byteString=atob(dataURI);
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}

// write the ArrayBuffer to a blob, and you're done
var bb = new Blob([ab]);
saveAs(bb,filename); //pass blob and file name
}

The saveAs() function on line 13 is a method defined in the FileSaver.js which you had already downloaded. Just give a reference to this file in your web resource and the file will be downloaded smoothly.



1 Comment

Leave a Reply

*

code