问题在于没有提示http内容显示的方式。
解决办法:为程序提供一个downLoadFile的方法,通过request和response结合流传输数据:
//为浏览器提供下载功能的方法(不会直接从浏览器打开文件)
public void downLoadFile(){
try{
//通过jsp页面的参数获取需要下载的文件的id,通过id获取文件
String fileId = this.getRequest().getParameter("fileId").toString();
TzgSpzgInFile ltzgSpzgInFile= tzgSpzgInFileManager.getById(fileId);
//获取下载存放的路径
HttpServletResponse response=this.getResponse();
String realpath = ServletActionContext.getServletContext().getRealPath("/");
File file = new File(realpath+ltzgSpzgInFile.getFilepath());
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
//设置内容类型,设置http响应头,文件内容显示方式(支持ie下载图片和txt)
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
} catch (Exception e) {
e.printStackTrace();
}
}
}
在前台jsp页面中获取数据库字段的参数值,调用给后台的action,路径下对应方法,并将获取到的id以及下载路径传递:
<td><a href="${ctx}/zg/TzgSpzgIn/downLoadFile.do?fileId=${item.id}" download="${item.filename} ">下载</a></td>