6

I am working on a grails application, it has a file sharing feature. It uploads files onto the server and allows user to download the file from server. I used the following code for this :

def file = new java.io.File(filePath)
response.setContentType( "application-xdownload")
response.setHeader("Content-Disposition", "attachment;filename=${fileName}")
response.getOutputStream() << new ByteArrayInputStream(file.getBytes())

This code works fine for small files but when the size of file is increased, i.e. >100MB, it gives me the following error :

java.lang.OutOfMemoryError: Java heap space

So, what can I do to make my application be able to download large files ? Thanks

Eddard Stark
  • 3,575
  • 8
  • 35
  • 51

1 Answers1

9

Instead of loading the file into memory, replace

response.getOutputStream() << new ByteArrayInputStream(file.getBytes())

With:

file.withInputStream { response.outputStream << it }
tim_yates
  • 167,322
  • 27
  • 342
  • 338