服务器下载文件
一、通过struts配置文件下载
1.前台页面:
<li> <a href="cbim/CbimAction!downloadFiles.action" target="_blank" >模板下载</a> </li>
2.后台action:
private InputStream inputStream;//get,set方法 private String fileName;//get,set方法 public String downloadFiles(){ String path="D://导入模板/信息导入模板-20160215.xlsx"; try { inputStream =new FileInputStream(path); fileName=new String("信息导入模板.xlsx".getBytes(),"ISO8859-1"); } catch (FileNotFoundException e) { e.printStackTrace(); }catch (UnsupportedEncodingException e) { e.printStackTrace(); } return "downloadFiles"; }
3.struts配置文件:
<result name="downloadFiles" type="stream">
<!--指定下载文件的类型 -->
<param name="contentType">application/vnd.ms-excel</param>
<!-- inputName默认值是inputStream -->
<param name="inputName">inputStream</param>
<param name="contentDisposition">
attachment;filename="${fileName}"
</param>
<param name="bufferSize">2048</param>
</result>
二、通过HttpServletResponse下载:
public void downloadDataPdf() throws Exception {
InputStream is = new BufferedInputStream(new FileInputStream(new File("D://毕业证.pdf"))); HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("application/pdf"); OutputStream os = response.getOutputStream(); byte[] readByte = new byte[4096]; int c; while ((c = is.read(readByte)) != -1) { os.write(readByte,0,c); } os.flush(); if (os != null) { os.close(); } if (is != null) { is.close(); }
}
public void downloadDataPdf() throws Exception {
InputStream is = new BufferedInputStream(new FileInputStream(new File("D://毕业证.pdf"))); HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("application/pdf"); OutputStream os = renderExcel(response, "毕结业证书.pdf"); byte[] readByte = new byte[4096]; int c; while ((c = is.read(readByte)) != -1) { os.write(readByte,0,c); } os.flush(); if (os != null) { os.close(); } if (is != null) { is.close(); }
}
public OutputStream renderExcel(HttpServletResponse response, String docName) {
return render("application/x-msdownload;charset=UTF-8", docName, response);
}
public static OutputStream render(String contentType, String docName, HttpServletResponse response) {
OutputStream outStream = null;
try {
response.setContentType(contentType);
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
String agent = ServletActionContext.getRequest().getHeader("USER-AGENT");
// 处理火狐浏览器,文件名编码问题
if (agent.indexOf("Firefox") > -1) {
docName = new String(docName.getBytes("GB2312"), "ISO-8859-1");
} else {
docName = URLEncoder.encode(docName, "utf-8");
}
response.setHeader("Content-disposition", "attachment;filename=" + docName);
outStream = response.getOutputStream();
}catch (IOException e) {
log.error(e.getMessage(), e);
}
return outStream;
}