我有一个 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/