Groovy Grails,如何在Controller的响应中流式传输或缓冲大文件?
发布时间:2020-12-14 16:34:39 所属栏目:大数据 来源:网络整理
导读:我有一个控制器连接到url来检索csv文件. 我可以使用以下代码在响应中发送文件,这可以正常工作. def fileURL = "www.mysite.com/input.csv" def thisUrl = new URL(fileURL); def connection = thisUrl.openConnection(); def output = connection.content.te
我有一个控制器连接到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() 但是,我认为这种方法对于一个大文件是不合适的,因为整个文件被加载到控制器内存中. 我想要能够通过块读取文件块,并通过块将文件写入响应块. 有任何想法吗? 解决方法
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() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |