title: Spring : Download file from REST controller
body: <p>I work on a Spring project to make a web app so there is a Tomcat server which permit me to lunch my web app.<br>
  I've got 2 functionalities on this web app, the first permit me to upload a file on a Postgresql Database (it's works correctly). But after that, i want to be able to download this file.  </p>
  
  <p>This is my method on my service.</p>
  
  <pre><code>public byte[] download(Integer id){
      Line line = getById(Line.class, id);
      int blobLenght;
      byte[] fileToReturn = null;
      Blob file = line.getFile();
      blobLenght = (int)file.length();
      fileToReturn = file.getBytes(1,blobLenght);
      return fileToReturn;
  }
  </code></pre>
  
  <p>On my RestController, i have a method with annotation @RequestMapping.
  And this method return a ResponseEntity. On the method after, lineService is inject (@Autowired) on the top of my class.</p>
  
  <pre><code>@RequestMapping(value = "/download", method = RequestMethod.GET)
  public ResponseEntity&lt;?&gt; download(@RequestParam("id" Integer id)
  {
      byte[] fileToDownload = lineService.download(id);
      return new ResponseEntity&lt;byte[]&gt;(fileToDownload,HttpStatus.OK);
  }
  </code></pre>
  
  <p>I have made an effort to simplify as much as possible the method.</p>
  
  <p>This is my problem. Indeed, I realize a method which works when i make some requests one by one. But, the server must be able to support receiving a lot of requests at the same time. And for now, when I test with many request in same time, i've got an OutOfMemoryError : Java heap space.<br>
  I tried to implement Stream on the method 'download' but I get the same error. My implementation of the streams could not be well done.
  I  tried many solution found on internet and this is the last that I implement :</p>
  
  <pre><code>public ResponseEntity&lt;byte[]&gt; download(Integer id){
      Line line = getById(Line.class, id);
      HttpHeaders headers = new HttpHeaders();
      InputStream is = line.getFile().getBinaryStream;
      byte[] fileToReturn = IOUtils.toByteArray(is);
      headers.setCacheControl(CacheControl.noCache().getHeaderValue());
      ResponseEntity&lt;byte[]&gt; responseEntity = new ResponseEntity&lt;byte[]&gt;(fileToDownload,HttpStatus.OK);
      return responseEntity;
  }
  </code></pre>
  
  <p>Do you know how i can update my program to answer at the requirement of the project, please ?<br>
  And if i'm on the good way could you tell my where is my mistake or if you have some suggestions, please ?  </p>
  
  <p>Thanks you for your help ! </p>
  
  <p>PM.</p>