Wednesday, September 9, 2009

Sending Excel file for download from Servlet

Sending Excel file for download from Servlet

In the Tomcat environment you need to add an entry something like this one
to the MIME Type Mappings section of the Tomcat web.xml file. (I don't know
if you can put this in your project's web.xml.)

web.xml

xls
application/msexcel



SomeAction.java
.
.
.
public static final String CONTENT_TYPE_APP_OCTET_STREAM =
"application/octet-stream";
public static final String CONTENT_TYPE_APP_MSEXCEL = "application/
msexcel";
.
.
.
protected void doFileDownload(HttpServletResponse response, String
fileName, String filePath, boolean bFlag) {
try {
File file = new File(filePath + fileName);
String contentType = null;
String headerInfo = null;

if (file.exists()) {
if (type) {
contentType = CONTENT_TYPE_APP_OCTET_STREAM;
headerInfo = "attachment; filename=\"" + fileName +
"\"";
} else {
contentType = CONTENT_TYPE_APP_MSEXCEL;
headerInfo = "inline; filename=\"" + fileName + "\"";
} // end if

response.setContentType(contentType);
response.setHeader("Content-Disposition", headerInfo);
response.setContentLength((int)file.length());

// set output stream to the response's output stream
ServletOutputStream servletOut = response.getOutputStream();

// now read file
byte[] dataRead = new byte[(int)file.length()];
FileInputStream fileIn = new FileInputStream(file);

// read in byte data from file and store in byte array
fileIn.read(dataRead, 0, (int)file.length());

// close file
if (fileIn != null) {
fileIn.close();
} // end if

// write the file to output stream
servletOut.write(dataRead);

// flush the output stream
servletOut.flush();
}
else
{
// TODO: handle File Not Found error here
} // end if
}
catch (Exception ex)
{
// TODO: handle Exception here
}
}

No comments: