【问题标题】:Vaadin 8 - Download Button for a text file with String contentVaadin 8 - 带有字符串内容的文本文件的下载按钮
【发布时间】:2018-01-24 13:13:18
【问题描述】:

我想将String 内容分配给一个变量,并使用户能够将该字符串下载为文本文件。 我知道有来自 Vaadin 8 的 FileDownloader 我可以使用,但我不想要静态文件/图像下载功能,而是可以下载 文本文件动态字符串内容 > 在浏览器中。

【问题讨论】:

    标签: scala stream vaadin vaadin8


    【解决方案1】:

    FileDownloader 使用的 Vaadin 中的资源接口有点麻烦。对于动态创建的内容尤其如此,您希望将其生成推迟到用户实际单击下载按钮之后,这在典型的 Vaadin 应用程序中很常见。

    Viritin 插件

    因此,我建议将Viritin add-on 添加到您的应用程序中。使用其中的DownloadButton 组件,大大简化了使用。

    这是一个简单的例子:

    DownloadButton simple = new DownloadButton(out -> {
        try {
            out.write("Foobar".getBytes());
        } catch (IOException ex) {
            // exception handling
        }
    }).withCaption("Simple Download");
    

    要查看更完整的示例,请参阅 Viritin 项目中的the tests。如果您仔细阅读DownloadButton类的源代码,您还可以从该项目中看到“原始解决方案”。

    PS。我是 Viritin 的作者,因此有点偏向于建议它的用法,但我也与 Vaadin 为 Vaadin Ltd 合作了十多年。

    【讨论】:

      【解决方案2】:

      这是 Scala 中的一个简单解决方案。我们创建了一个扩展 VerticalLayout 的ReportDownloader 组件。它包含一个“下载”按钮,可触发浏览器中的文本文件下载。

      import com.vaadin.ui.{Button, VerticalLayout}
      import com.vaadin.server._
      import java.io.{ByteArrayInputStream}
      
      class VaadinStringStream(str : String, browserFileNameSuggestion : String) extends ConnectorResource {
      
        override def getMIMEType: String = "text/plain"
        override def getFilename: String = browserFileNameSuggestion
        override def getStream: DownloadStream = new DownloadStream(
          new ByteArrayInputStream(str.getBytes), getMIMEType, getFilename
        )
      }
      
      class ReportDownloader extends VerticalLayout{
        val btn = new Button("DOWNLOAD")
        this addComponent btn
      
        val stream = new VaadinStringStream("This is a sample txt file content", "report.txt")
        new FileDownloader(stream).extend(btn)
      }
      

      VaadinStringStream 将动态字符串内容和浏览器的建议文件名作为参数。

      【讨论】:

      • 看起来是一个有效的解决方案,但是当显示下载按钮时,文件内容已经存储到内存中。因此,我建议仅在下载文件的内容很小并且只有一堆下载链接的情况下才使用这种解决方案。否则,这将导致服务器大量使用内存。
      • 是的,你是对的。后来我将内存中的字符串 "This is a sample txt file content" 更改为返回字符串的 lambda。 class VaadinStringStream(str : () => String) extends ConnectorResource 放弃字符串并仅使用 Streams 将是一个更好的解决方案。
      猜你喜欢
      • 2021-10-05
      • 2012-10-14
      • 2017-11-08
      • 1970-01-01
      • 2019-10-06
      • 1970-01-01
      • 2018-12-29
      • 2012-07-24
      • 1970-01-01
      相关资源
      最近更新 更多