title: Memory Efficient File/Image Upload in Java?
body: <p>I want to upload images which are 2MB - 10MB to my server and save them directly to hard disk. The goal is to save as much Heap Memory of my JVM as I can, because if user upload concurrently my sysem should not crash.</p>
  
  <p>This is how I do it at the moment. When a request with an upload come into my Controller I do:</p>
  
  <pre><code>CommonsMultipartFile file = (CommonsMultipartFile) request.getFile('image')
  InputStream inputStream = file.inputStream
  byte [] byteFile = inputStream.getBytes()
  
  try{
    def fullPath = // some image path and file name
    def newFile = new FileOutputStream(fullPath)
    newFile.write(byteFile)
    newFile.close()
  }
  catch(IOException e){ }
  </code></pre>
  
  <p><a href="https://stackoverflow.com/questions/12142069/scale-large-images-using-java-and-asyncscalr">Here</a> I read that there is ImageIO and java.awt.Toolkit, where Toolkit is supposed to be the fastest to store the file.  </p>
  
  <p>How can I improve my upload to use as less heap as possible and upload as fast as possible? </p>
  
  <p>Alternative 1: </p>
  
  <p>An alternative could be to:</p>
  
  <pre><code>CommonsMultipartFile file = (CommonsMultipartFile) request.getFile('image')
  def fullPath = // some image path and file name
  file.transferTo(new File(fullPath))
  </code></pre>
  
  <p>Which one is better?</p>