Scala Playframework发送文件 [英] Scala Playframework send file

查看:84
本文介绍了Scala Playframework发送文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据字符串,该字符串是从数据库中的数据获取的.我想将其发送给用户,但不创建文件的本地副本,例如

I have a string of data, which I get from data in my database. I want to send it to the user, but without creating a local copy of the file, something like

Ok(MyString).as("file/csv") 

但是它不起作用.我该怎么办?

But it is not working. How can I do it?

推荐答案

您可以通过将chunkedEnumerator结合使用来实现.我还使用withHeaders来指定Result的内容类型和配置为附件",以便客户端将其解释为要下载的文件(而不是在浏览器本身中打开).

You can do this by using chunked with an Enumerator. I've also used withHeaders to specify the content type and disposition of the Result to "attachment", so that the client will interpret it as a file to download (rather than opening in the browser itself).

import play.api.libs.iteratee.Enumerator

val myString: String = ??? // the String you want to send as a file

Ok.chunked(Enumerator(myString.getBytes("UTF-8")).andThen(Enumerator.eof))
  .withHeaders(
     "Content-Type" -> "text/csv",
     "Content-Disposition" -> "attachment; filename=mystring.csv"
  )

根据从数据库中获取的类型,这可能不会立即编译.

This might not compile right away, depending on the types you're getting from the database.

请考虑一下,这也应该起作用(没有Enumerator):

Come to think of it, this should also work (without the Enumerator):

 Ok(myString).withHeaders( /* headers from above */ )

这篇关于Scala Playframework发送文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆