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

Jul*_*oye 13 grails response grails-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()
Run Code Online (Sandbox Code Playgroud)

但是我认为这个方法不适合大文件,因为整个文件被加载到控制器内存中.

我希望能够通过块读取文件块,并通过块将文件写入响应块.

有任何想法吗?

ata*_*lor 23

Groovy OutputStreams可以直接与<<运算符一起使用InputStreams .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()
Run Code Online (Sandbox Code Playgroud)

  • 很好的解决方案,但请记住关闭inputStream.一个安全的替代方法是使用connection.withInputStream {...} (3认同)