【发布时间】:2018-01-24 13:13:18
【问题描述】:
我想将String 内容分配给一个变量,并使用户能够将该字符串下载为文本文件。
我知道有来自 Vaadin 8 的 FileDownloader 我可以使用,但我不想要静态文件/图像下载功能,而是可以下载 文本文件的 动态字符串内容 > 在浏览器中。
【问题讨论】:
标签: scala stream vaadin vaadin8
我想将String 内容分配给一个变量,并使用户能够将该字符串下载为文本文件。
我知道有来自 Vaadin 8 的 FileDownloader 我可以使用,但我不想要静态文件/图像下载功能,而是可以下载 文本文件的 动态字符串内容 > 在浏览器中。
【问题讨论】:
标签: scala stream vaadin vaadin8
FileDownloader 使用的 Vaadin 中的资源接口有点麻烦。对于动态创建的内容尤其如此,您希望将其生成推迟到用户实际单击下载按钮之后,这在典型的 Vaadin 应用程序中很常见。
因此,我建议将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 合作了十多年。
【讨论】:
这是 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 将是一个更好的解决方案。