Creating custom downloads using JSP

This code snippet will help you to create custom/runtime downloads upon user request. In this code snippet, the code will create a download for an image in the server.

String fileName = config.getServletContext().getRealPath("") + "image.jpg"; 
String displayFileName = "myFile.jpg"; 
long fileLength; 
byte[] byteStream;
File fileToDownload = new File(fileName); 
FileInputStream fileInStream = new FileInputStream(fileToDownload); 
OutputStream outStream = response.getOutputStream();
fileLength = fileToDownload.length(); 
byteStream = new byte[(int)fileLength]; 
fileInStream.read(byteStream, 0, (int)fileLength);
response.setContentType("image/jpg"); 
response.setContentLength((int)fileLength); 
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); 
response.setHeader("Pragma", "no-cache"); 
response.setHeader("Content-Disposition", "attachment; filename=" + displayFileName);
fileInStream.close(); 
outStream.write(byteStream); 
outStream.flush();

Here, evenif the browser can display the JPEG image coming from the the server as the response, will ask the user to either “Open” or “Save” it. B’ coz we are setting the  “Content-Disposition” header to “attachment”.

Advertisements