【问题标题】:Text file download in Visualforce pageVisualforce 页面中的文本文件下载
【发布时间】:2016-05-04 11:50:16
【问题描述】:

我的 visualforce 页面中有一个下载按钮,单击该按钮必须下载文本文件(.txt 格式)。此文本文件将使用存储在自定义对象的文本字段中的数据动态创建。现在,我正在努力实现这个简单的下载功能,而无需创建附件或文档对象。有没有可能将内容下载为纯文本文件的方法?有人可以帮我解决这个问题吗?

我已经尝试了下面的 visualforce 代码,但它没有下载任何文件。

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

其中 getEncodedData 将是文本文件主体。

顶点代码:

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

P.N:我试图在不创建附件的情况下实现这一点,只是因为创建的文件以后不会被重用。

非常感谢任何帮助..!!

【问题讨论】:

    标签: salesforce apex-code visualforce apex


    【解决方案1】:

    让你按钮打开一个新标签(如果我没记错的话,target="_blank")并加载一个新页面。您可以将普通页面与合并字段和所有内容放在一起,您只需要更改内容类型:

    <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(请注意,可用的内容类型比他们在该页面上列出的要多)。

    【讨论】:

      【解决方案2】:

      JavaScript Textdownload 比使用 href 更简单,尤其是在这种情况下 :-)

      这是确切的流程。

      Visualforce 代码:

      <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 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);
      }
      

      在上述代码中,“filename”和“getData”变量将在 Apex 控制器中调用 Apex 方法“fileContent”时设置。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-08
        • 2011-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多