• Home
  • Contact Me
  • About Me
  • Resources
  • Favorites
  • Earn Money

Wednesday, July 23, 2008

Implementation of SaveAs functionality in JSP as well as Servlet

Implementing SaveAs functionality in java/j2ee may not be a big deal. However for developers like me it is sounding difficult.
Every complex problem has a simple solution - atleast I believe that.
For those folks who found implementing SaveAs functionality in web application is difficult, this article will crack it.

Description: Implementing save as functionality in jsp as well as using servlet.
Assumptions: I assume that content of the file is already generated or file is generated in the server. Also assumes that we know the file type. Now browser should ask the user to save the file in desired location or open the file in appropriate editor.

Implementation in JSP:
FileType: excel
Code: response.setContentType("application/vnd.ms-excel")
FileType: pdf
Code: response.setContentType("application/pdf")

FileType: text
Code: response.setContentType("text/plain")

FileType: csv
Code: response.setContentType("application/octet-stream")
FileType: csv
Code: response.setContentType("application/octet-stream")

Additionally you can use following statement which will set the filename
response.setHeader ("Content-Disposition", "attachment;filename=\""+ fileName +"\"");

Implementation in Servlet: In servlet you can do something like below:
//set the content type based on file type
if(fileType.equalsIgnoreCase("PDF")){
response.setContentType ("application/pdf");
}
if(fileType.equalsIgnoreCase("TEXT")){
response.setContentType ("text/plain");
}
if(fileType.equalsIgnoreCase("CSV")){
response.setContentType ("application/octet-stream");
}

//set the file name
response.setHeader ("Content-Disposition", "attachment;filename=\""+ fileName +"\"");

//get the file content

File file = new File(filePath);
// Create the byte array to hold the data
byte[] bytes = null;
InputStream is;
try {
is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
// File is too large
}
bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < numread="is.read(bytes,">= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset <>
response.setContentLength(bytes.length);
response.getOutputStream().write(bytes);
response.getOutputStream().close();


Common Mistake: I have seen developers try to write the file content into response object inside jsp which is illegal because server is already finished writing onto the response.



Regards
Monu

No comments: