title: How to download a file using a Java REST service and a data stream
body: <blockquote>
  <p>I have 3 machines:</p>
  <ol>
  <li>server where the file is located<br></li>
  <li>server where REST service is running ( Jersey) <br></li>
  <li>client(browser) with access to 2nd server but no access to 1st server</li>
  </ol>
  </blockquote>
  <p>How can I directly (without saving the file on 2nd server) download the file from 1st server to client's machine? <br>
  From 2nd server I can get a <strong>ByteArrayOutputStream</strong> to get the file from 1st server, can I pass this stream further to the client using the REST service?</p>
  <p>It will work this way?</p>
  <p>So basically what I want to achieve is to allow the client to download a file from 1st server using the REST service on 2nd server (since there is no direct access from client to 1st server) using only data streams (so no data touching the file system of 2nd server).</p>
  <p>What I try now with EasyStream library:</p>
  <pre><code>final FTDClient client = FTDClient.getInstance();
  
  try {
      final InputStreamFromOutputStream &lt;String&gt; isOs = new InputStreamFromOutputStream &lt;String&gt;() {
          @Override
          public String produce(final OutputStream dataSink) throws Exception {
              return client.downloadFile2(location, Integer.valueOf(spaceId), URLDecoder.decode(filePath, &quot;UTF-8&quot;), dataSink);
          }
      };
      try {
          String fileName = filePath.substring(filePath.lastIndexOf(&quot;/&quot;) + 1);
  
          StreamingOutput output = new StreamingOutput() {
              @Override
              public void write(OutputStream outputStream) throws IOException, WebApplicationException {
                  int length;
                  byte[] buffer = new byte[1024];
                  while ((length = isOs.read(buffer)) != -1) {
                      outputStream.write(buffer, 0, length);
                  }
                  outputStream.flush();
              }
          };
          return Response.ok(output, MediaType.APPLICATION_OCTET_STREAM)
              .header(&quot;Content-Disposition&quot;, &quot;attachment; filename=\&quot;&quot; + fileName + &quot;\&quot;&quot;)
              .build();
      }
  }
  </code></pre>
  <p><strong>UPDATE2</strong></p>
  <p>So my code now with the custom MessageBodyWriter looks simple:</p>
  <pre><code>ByteArrayOutputStream baos = new ByteArrayOutputStream(2048) ;
  client.downloadFile(location, spaceId, filePath, baos);
  return Response.ok(baos).build();
  </code></pre>
  <p>But I get the same heap error when trying with large files.</p>
  <p><strong>UPDATE3</strong>
  Finally managed to get it working !
  StreamingOutput did the trick.</p>
  <p>Thank you @peeskillet ! Many thanks !</p>