1
votes

I have a download button in my visualforce page, on clicking which a text file(.txt format) has to be downloaded. This text file will be created dynamically with the data stored in a Text field of a custom object. Now I am struggling to acheive this simple download functionality without creating Attachments or Document Objects. Is there any possible way to download content as plain text file? Could some one please help me with this?

I have tried the below visualforce code, but it is not downloading any files.

<a href="data:text/plain;charset=utf-8;base64,{!getEncodedData}"> Download License </a></apex:outputLabel>

where getEncodedData will be the text file body.

Apex code:

getEncodedData = EncodingUtil.base64Encode(Blob.valueOf(strContent));

P.N : I am trying to achieve this without creating Attachments, simply because the created file will not be reused later.

Any help is really appreciated..!!

2

2 Answers

0
votes

Make you button open a new tab (target="_blank" if I recall correctly) and load up a new page. You can put together a normal page with merge fields and everything, you just need to change the content type:

<apex:page standardController="Account" contentType="application/vnd.ms-excel">

https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_styling_content_type.htm (note that there are more content types available than what they list on that page).

0
votes

JavaScript Textdownload made it simple than the href usage, especially in this case :-)

And here is the exact flow.

Visualforce Code:

<apex:outputLabel onClick="javascript:fnDownloadContent('{!ID}','{!compId}');" >Download</apex:outputLabel>  
<apex:actionfunction name="actDnldContent" action="{!fileContent}" reRender="" oncomplete="javascript:download('{!filename}','{!getData}');">
<apex:param name="Id" value="" assignTo="{!Id}" />
<apex:param name="compId" value="" assignTo="{!CompId}"/>                                                                     
</apex:actionfunction>

JavaSript function:

function fnDownloadContent(ID, compID)
{
    actDnldContent(ID, compID);         
}  
function download(filename,text) 
{
    var element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    element.setAttribute('download', filename);
    element.style.display = 'none';
    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);
}

In the above code, the 'filename' and 'getData' variables will be set on calling the Apex method 'fileContent' in the Apex Controller.