Return binary data with a Servlet

There are a couple possibilities. One way (if the binary file is in the subtree of your docroot) is to do a redirection inside your servlet to the binary file as shown in following example:

GetFileThroughServlet1.java:

import javax.servlet.http.*;
import javax.servlet.*;
 
import java.io.*;
 
public class GetFileThroughServlet1 extends HttpServlet
{ 
   public void doGet (HttpServletRequest request,
                       HttpServletResponse response) 
   {
      try {
         response.sendRedirect("http://www.yourdomain.com/test.zip");
      } catch (Exception e) {
      }
   }
}

A second, more flexible way, is to return a file as a binary stream. The file doesn’t need to be in the subtree of a docroot, for example you can get it off the network or from a database.

GetFileThroughServlet2.java:

import javax.servlet.http.*;
import javax.servlet.*;
 
import java.io.*;
 
public class GetFileThroughServlet2 extends HttpServlet
{ 
   public void doGet (HttpServletRequest request,
                       HttpServletResponse response) 
   {
      try {
         String pathToFile = "/dir1/dir2/dir3/";
         String fileToUpload = "test.zip"; 
         int filesize = 40768;   // test.zip filesize
  
         // set content type to octet-stream = binary file
         response.setContentType("application/octet-stream");
  
         // Content-Disposition is a field to specify presentation of entity or file name
         response.setHeader("Content-Disposition", "attachment; filename="" + fileToUpload + "";");
 
         response.setHeader("Cache-Control", "no-cache");         
 
         response.setContentLength(filesize);
 
         ServletOutputStream sos = response.getOutputStream(); 
         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(pathToFile + fileToUpload)); 
         int data; 
         while((data = bis.read()) != -1) {  
            sos.write(data); 
         }  
         bis.close(); 
         sos.close();
      }
      catch(Exception e) {
      }
   }
}