+ Start a Discussion
ForceLoverForceLover 

Pass parameter to javascript function dynamically

Hi Everyone,

 

I want to pass my attachment body which i'm querying in the script to the javascript function

base64_decode (some base64variable).

Actually attachement body is of type Base64.

 

<script>
  var existingSel = document.getElementById('select_0');
  sforce.connection.sessionId = '{!$Api.Session_ID}';
 
  var qr = sforce.connection.query("Select Id,ParentId, Name,body,ContentType From Attachment where ParentId=:'0039000000InSjOAAV'") ;
  var records = qr.getArray(“records”)
 
  for (var i=0;i<qr.records.length;i++)
  {
   alert(qr.records[i].Body);
  }

  function base64_decode (some variable) {
 
 ////////////////// Some Logic Here==========================
}
</script>

SarfarajSarfaraj

sforce.Base64Binary.prototype.decode is one method that will decode the encoded body.

 

sforce.Base64Binary.prototype.decode(a.getArray("records")[0].Body)

 

If possible avoid parsing in Javascript. Use the following approach instead:

http://www.salesforce.com/us/developer/docs/ajax/Content/sforce_api_ajax_queryresultiterator.htm#base64issue

ForceLoverForceLover

Hi Akram,

 

Thanks for the reply.Actually i'm trying to read word document body which is attached as a attachment to a record.The attachment body is of type base64 when i'm debug for attachment.body it is displaying as blob[length] ,can you please suggest me how to read the word doc body please share some code.

 

Regards,

Anil Kumar

 

SarfarajSarfaraj

Hi Anil

 

As I said earlier Attachment body is of type base64. It is encoded text. If you need to convert it back to its binary form you need to decode it using the method I quoted earlier. Next step depends on what you want to do with this content. Here is the code that I have tried till now. I have tested it with text attachments only. Hope this helps.

 

<apex:page controller="downloadMyFileController">
<apex:includeScript value="{!URLFOR($Resource.filesaver)}"/>
<script src="/soap/ajax/28.0/connection.js"/>
<script type="text/javascript">
sforce.connection.sessionId = '{!$Api.Session_ID}';
var qr = sforce.connection.query("Select Id, Body, Name From Attachment Where Id = '{!fileId}'") ;
var records = qr.getArray("records");
saveAs(new Blob([sforce.Base64Binary.prototype.decode(records[0].Body)], {type: 'text/plain;charset=utf-8;charset=utf-8'}), 'file.txt');
</script>
</apex:page>

 

public with sharing class downloadMyFileController {
    public Id fileId{get;set;}
    public Attachment at{get;set;}
    public DownloadMyFileController()
    {
        fileId = ApexPages.currentPage().getParameters().get('id');
        at = [Select Id, Body, Name From Attachment Where Id = :fileId];
    }
}

Please elaborate your requirement if you need any further assistance.