1

I have a download text content functionality in my visualforce page, on clicking which a text file(.txt format) will be downloaded. This file will be created dynamically with the data stored in a Text field of a custom object. Now text file is getting downloaded but as empty file. Here, I am using a JavaScript function(which in turn will call action function to assign file content) on Onclick event. I could notice that my JS function is called after file download. Could somebody please tell me where I am getting wrong?

Javascript fn:

function fnDownloadContent(ID, compID)
{
actDnldContent(ID, compID);
}

Visualforce code:

    <apex:actionfunction name="actDnldContent" action="{!fetchContent}"  reRender="" >
        <apex:param name="Id" value="" assignTo="{!Id}" />
        <apex:param name="compId" value="" assignTo="{!CompId}"/>                                                                     
        </apex:actionfunction>
     <apex:outputLink value="data:text/plain;charset=utf-8;base64,{!getEncodedData}" html-download="description.txt" >
<a ref="javascript:fnDownloadContent('{!lstDet.ID}','{!lstDet.CompId}');">Download</a>
</apex:outputLink> 

Apex Controller code:

public String strContent { get; set; }
public String getEncodedData {get; set;}
public void fetchContent()
{
//Will be assigning text content here         
strContent = 'Hello';
getEncodedData = EncodingUtil.base64Encode(Blob.valueOf(strContent));     
}

So far, I could get the required content in a popup window after clicking on download, but it is not downloading any files.

2

Resolved the issue using the simple javaScript download function. Here the exact flow.

Visualforce Code:

<apex:outputLabel onClick="javascript:fnDownloadContent('{!lstDet.ID}','{!lstDet.compId}');" >Download</apex:outputLabel>  
<apex:actionfunction name="actDnldContent" action="{!dnld_Content}" 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 'dnld_Content' in the Apex Controller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.