I have written a code for downloading a file(blob in database table).I get a prompt while downloading but when i download it’s size increases and opens as a blank file or corrupted file.The controller calling 2 service methods downloadfile():- to get the blob type into a byte array.
downloadfilename() :- to get the filename stored in the database.
Code for Contoller
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
byte[] fileBytes = userService.downloadFile();
String filename = userService.downloadFileName();
String fileType = filename.substring(filename.indexOf(".")+1,filename.length());
System.out.println("FILETYPE IS :>>>>>>>>>>>>>>>"+fileType);
if (fileType.trim().equalsIgnoreCase("txt"))
{
response.setContentType( "text/plain" );
}
else if (fileType.trim().equalsIgnoreCase("doc"))
{
response.setContentType( "application/msword" );
}
else if (fileType.trim().equalsIgnoreCase("xls"))
{
response.setContentType( "application/vnd.ms-excel" );
}
else if (fileType.trim().equalsIgnoreCase("pdf"))
{
response.setContentType( "application/pdf" );
}
else if (fileType.trim().equalsIgnoreCase("ppt"))
{
response.setContentType( "application/ppt" );
}
else
{
response.setContentType( "application/octet-stream" );
}
response.setHeader("Content-Disposition","attachment; filename=\""+filename+"\"");
response.setHeader("cache-control", "no-cache");
response.setHeader("cache-control", "must-revalidate");
ServletOutputStream outs = response.getOutputStream();
outs.write(fileBytes);
outs.flush();
outs.close();
return null;
}
DAO CLASS goes like this..
public String downloadFile(){
String selectquery = "select * from upload_file where id=1";
System.out.println("inside after query");
ResultSet rs = stmt.executeQuery(selectquery);
while (rs.next()) {
fileBytes = rs.getBytes("description");
fileName = rs.getString("upload_filename");
System.out.println("**************************************"
+ fileName);
}
return fileName;
} catch (SQLException s) {
System.out.println(s);
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
You question is not really clear, but I think I know what you mean.
If a file is large (10MB) then you must specify the content length in the http header. If not the browsers will behave stange. (The exact limit 10MB is browser depended)