title: How can I put a downloadable file into the HttpServletResponse?
body: <p>I have the following problem: I have an <strong>HttpServlet</strong> that create a file and return it to the user that have to receive it as a download </p>
  
  <pre><code>byte[] byteArray = allegato.getFile();
  
  InputStream is = new ByteArrayInputStream(byteArray);
  Base64InputStream base64InputStream = new Base64InputStream(is);
  
  int chunk = 1024;
  byte[] buffer = new byte[chunk];
  int bytesRead = -1;
  
  OutputStream out = new ByteArrayOutputStream();
  
  while ((bytesRead = base64InputStream.read(buffer)) != -1) {
      out.write(buffer, 0, bytesRead);
  }
  </code></pre>
  
  <p>As you can see I have a <strong>byteArray</strong> object that is an array of bytes (<strong>byte[] byteArray</strong>) and I convert it into a file in this way:</p>
  
  <ol>
  <li><p>First I convert it into an <strong>InputStream</strong> object.</p></li>
  <li><p>Then I convert the <strong>InputStream</strong> object into a <strong>Base64InputStream</strong>.</p></li>
  <li><p>Finally I write this <strong>Base64InputStream</strong> on a <strong>ByteArrayOutputStream</strong> object (the <strong>OutputStream out</strong> object).</p></li>
  </ol>
  
  <p>I think that up to here it should be ok (is it ok or am I missing something in the file creation?)</p>
  
  <p>Now my servlet have to return this file as a dowload (so the user have to receive the download into the browser).</p>
  
  <p>So what have I to do to obtain this behavior? I think that I have to put this <strong>OutputStream</strong> object into the Servlet response, something like:</p>
  
  <pre><code>ServletOutputStream stream = res.getOutputStream();
  </code></pre>
  
  <p>But I have no idea about how exactly do it? Have I also to set a specific MIME type for the file?</p>