Groovy Grails, How do you stream or buffer a large file in a Controller's response?

前端 未结 1 388
孤街浪徒
孤街浪徒 2021-02-05 16:01

I have a controller that makes a connection to a url to retrieve a csv file.

I am able to send the file in the response using the following code, this works fine.

<
相关标签:
1条回答
  • 2021-02-05 16:47

    Groovy OutputStreams can take InputStreams directly with the << operator. The OutputStream will pull the data automatically with an appropriately sized buffer.

    The following should efficiently copy the data, even if the CSV is quite large.

    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()
    
    0 讨论(0)
提交回复
热议问题