download files with a spring controller
843841Oct 2 2006 — edited Aug 12 2008hey everyone,
i have a spring controller for downloading any kind of file. So far this works good. When i get the dialog box to save or open the file things go wrong.
In firefox i always see the .htm added at the back of my file which is a reference to my spring controller.
In IE the file always seems to be corrupted!!!
Could anyone point me in the right direction???!!!
thanks
Here is my code:
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView view = null;
if (request.getParameter("filename") != null) {
String filename = (String) request.getParameter("filename");
m_conf = new RmiServletConfig("eca2/variables");
String viewFilePath = m_conf.getInitParameter("viewFilePath");
File uFile = new File(viewFilePath + "/" + filename);
int fSize = (int) uFile.length();
if (fSize > 0 && uFile != null && uFile.isFile() && uFile.exists()
&& uFile.canRead()) {
String mimetype = request.getSession().getServletContext().getMimeType(
filename);
response.reset();
response.setContentType(mimetype);
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "max-age=0");
response.setHeader("Content-Disposition", "attachment; filename=\""
+ filename + "\"");
response.setContentLength(fSize);
byte[] fileBytes = getBytesFromFile(uFile);
FileCopyUtils.copy(fileBytes, response.getOutputStream());
response.getOutputStream().flush();
response.getOutputStream().close();
return null;
} else {
String message = "Could not get the file " + filename;
view = new ModelAndView("viewfile", "message", message);
}
view = new ModelAndView("viewfile");
} else {
String message = "No filename parameter specified";
view = new ModelAndView("viewfile", "message", message);
}
return view;
}
/**
* retrieves the file in a byte array
* @param file File the file to retrieve in byte array
* @return byte[] the byte array
* @throws IOException
*/
private byte[] getBytesFromFile(File file) throws IOException {
try
{
InputStream fileIn = new FileInputStream(file);
int len = fileIn.available();
byte bytes[] = new byte[len];
fileIn.read(bytes);
fileIn.close();
return bytes;
} catch(Exception e)
{
return null;
}
}