grails - Groovy Grails,如何在 Controller 的响应中流式传输或缓冲大文件?

标签 grails response grails-controller

我有一个 Controller 连接到一个 url 来检索一个 csv 文件。

我可以使用以下代码在响应中发送文件,这很好用。

    def fileURL = "www.mysite.com/input.csv"
    def thisUrl = new URL(fileURL);
    def connection = thisUrl.openConnection();
    def output = connection.content.text;

    response.setHeader "Content-disposition", "attachment;
    filename=${'output.csv'}"
    response.contentType = 'text/csv'
    response.outputStream << output
    response.outputStream.flush()

但是我认为这种方法不适用于大文件,因为整个文件都被加载到 Controller 内存中。

我希望能够逐块读取文件并将文件逐块写入响应块。

有任何想法吗?

最佳答案

Groovy OutputStreams可以直接使用 << 获取 InputStreams运算符(operator)。 OutputStream 将使用适当大小的缓冲区自动提取数据。

即使 CSV 非常大,以下内容也应该有效地复制数据。

def fileURL = "www.mysite.com/input.csv"
def thisUrl = new URL(fileURL);
def connection = thisUrl.openConnection();
def cvsInputStream = connection.inputStream

response.setHeader "Content-disposition", "attachment;
filename=${'output.csv'}"
response.contentType = 'text/csv'
response.outputStream << csvInputStream
response.outputStream.flush()

关于grails - Groovy Grails,如何在 Controller 的响应中流式传输或缓冲大文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2824486/

相关文章:

unit-testing - 需要 Grails 单元测试帮助

grails用闭包的可选参数替换方法

Grails Spring Security 示例应用程序不工作

grails - 如何在Grails中注册自定义json解串器/解析器?

grails - (未保存的)groovy 中多对多关系中的数据

javascript - 在 Grails 中动态更改模式内容

java - 查找同一字符的最长连续子序列的长度

java - 解析从 Google 距离矩阵 API 发送的 Json 响应

javascript - 从 Javascript 中的 Action 输出响应

angularjs - 从angularjs 1.5上传图像到grails 3作为byte []并将其保存在postgresql中作为bytea