使用struts2的方式完成下载
对于下载excel2003,contentType如此设置
<result name="success" type="stream">
<param name="contentType">application/vnd.ms-excel</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename="${#request.filename}.xls"</param>
<!-- <param name="contentDisposition">attachment;filename="${fileName}"</param> -->
<param name="bufferSize">1024</param>
</result>
对于下载excel2007,contentType如此设置
<param name="contentType">application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</param>
注:
1.<param name="contentDisposition">中的attachment表示以附件形式保存到浏览器,而不是直接输在浏览器页面,${fileName} 为action中的文件名变量,action中需要声明该变量并写getter和setter方法
2.<param name="inputName">中的inputStream为输入流变量名,需要在action中声明并写getter和setter方法
在action中
private InputStream inputStream;//输入流变量
private String fileName;//下载文件名
关键代码:
public String download(){
try {
//获取模板文件的id,通过id,来查询出模板文件的信息,获取路径path
Integer id=applicationTemplate.getId();
ApplicationTemplate applicationTemplate=applicationTemplateService.findApplicationTemplateById(id);
//获取路径path
// String path=applicationTemplate.getPath();
String path = "/download";
//将路径path转成输入流
InputStream in=new FileInputStream(new File(ServletActionContext.getServletContext().getRealPath("")+path));
//将输入流的数据放置到模型驱动对象的InputStream的属性中
applicationTemplate.setInputStream(in);
//获取下载文件的名字
String filename = applicationTemplate.getName();
filename = new String(filename.getBytes("gbk"),"iso-8859-1");
request.setAttribute("filename", filename);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "success";
}
--------------------------------------------------------------------------------------
* @Return: 一:使用javaweb的方式完成下载,return null
*/
// public String download(){
// try {
// //1:获取传递的申请模板ID,使用申请模板ID,查询申请模板信息,获取路径path
// Integer id = elecApplicationTemplate.getId();
// ElecApplicationTemplate applicationTemplate = elecApplicationTemplateService.findApplicationTemplateByID(id);
// //获取路径path
// String path = applicationTemplate.getPath();
// //2:将路径path转化成输入流,将输入流的信息,写到输出流(从response对象中获取输出流)
// InputStream in = new FileInputStream(new File(ServletActionContext.getServletContext().getRealPath("")+path));
//
// //获取申请模板文件的文件名
// String filename = applicationTemplate.getName();
// filename = new String(filename.getBytes("gbk"),"iso-8859-1");
//
// //设置文件下载的格式
// response.setContentType("application/msword");
// //设置附件的数据处理方式
// response.setHeader("Content-disposition", "attachment;filename="+filename+".doc");
// //设置下载附件的缓冲区大小
// response.setBufferSize(1024);
//
// OutputStream out = response.getOutputStream();
// for(int b=-1;(b=in.read())!=-1;){
// out.write(b);
// }
// out.close();
// in.close();
// } catch (Exception e) {
// e.printStackTrace();
// }
// return null;
// }