2010-05-13 3 views
13

URL에 연결하여 csv 파일을 검색하는 컨트롤러가 있습니다.Groovy Grails, 컨트롤러의 응답으로 큰 파일을 스트리밍하거나 버퍼링하는 방법은 무엇입니까?

다음 코드를 사용하여 응답 파일을 보낼 수 있지만 정상적으로 작동합니다.

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() 

그러나이 방법은 전체 파일이 컨트롤러 메모리에로드되므로 큰 파일에는 적합하지 않다고 생각합니다.

청크로 파일 청크를 읽고 청크로 응답 청크에 파일을 쓸 수 있기를 원합니다.

아이디어가 있으십니까?

답변

23

Groovy OutputStreams<< 연산자로 직접 InputStream을 사용할 수 있습니다. 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() 
+3

좋은 해결책이지만 inputStream도 닫아야합니다. 안전한 대안은 connection.withInputStream {...}을 사용하는 것입니다. – stenix

관련 문제