-1
我已經編寫了一個下載文件的代碼(數據庫表中的blob)。我在下載時收到提示,但是當我下載它的大小增加並打開爲空白文件或損壞的文件。控制器調用2個服務方法downloadfile(): - 將blob類型獲取到一個字節數組中。從數據庫表中下載文件(Mysql,spring)
downloadfilename(): - 獲取存儲在數據庫中的文件名。 代碼位指示
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類是這樣的..
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;
}