实现文件下载

String path = request.getContextPath();
String corejs = path + "/core/js";
request.setAttribute("path", path);
request.setAttribute("corejs", corejs);

var url = "${path}/sxElectronicTemplate/readontheweb.jsp?unid="+unid;
window.location = encodeURI(url);

<%@ page contentType="text/html;charset=GBK"%>
<!--
    功能:文件下载
-->
<%
InputStream is = null;
OutputStream os = null;
try{
  String unid = request.getParameter("unid");
  AppFile appFile = new AppFileManager(JNDI).doFindBeanByKey(unid);
  appFile = null == appFile ? new AppFile() : appFile;
  String filename = appFile.getFile_name();

  Blob file_data = appFile.getFile_data();
   if(null != file_data && file_data.length() > 0){
    is = appFile.getFile_data().getBinaryStream();
   }else{
    String filepath = new AppFileServiceBusiness().getAttrPath(appFile.getFile_path());
   filepath = filepath.replaceAll("\\\\", "/"); // 反斜杠("\")属于转义符号,在传参之前必须先转化成正斜杠("/")
  
   File file = new File(filepath);
   if(null == file || !file.exists()){
    StringBuffer script = new StringBuffer();
    script.append("<script language='javascript'>");
    script.append("alert('文件不存在!');");
    script.append("history.go(-1);");
    script.append("</script>");
    out.println(script.toString());
    return;
   }else{
    is = new FileInputStream(file);
   }
   }
  
  //目前文件实体没有保存到数据库中,而是直接保存到服务器上,所以这边可通过文件路径直接读取
  response.addHeader("Content-Disposition","attachment; filename="+URLEncoder.encode(filename,"UTF8"));
  response.setContentType("application/msword");
  response.setHeader("Pragma", "public");
  response.setHeader("Cache-Control", "max-age=0");

  int bytesRead;
  byte[] buffer = new byte[4096];
  os = new BufferedOutputStream(response.getOutputStream());
  while((bytesRead = is.read(buffer, 0, buffer.length)) != -1) {
     os.write(buffer, 0, bytesRead);
  }
  response.flushBuffer();
  os.close();
  is.close();

  // 后面两句必须加上去,否则tomcat在把jsp编译成servlet之后,会加上释放jsp引用对象的代码,会调用response.getWriter(),
  // 因为这个方法是和response.getOutputStream()相冲突的!所以会出现以上这个异常。
  // 注:这两句不能放在finally语句块中,否则当文件不存在时,会导致无法输出提示信息
  out.clear();
  out = pageContext.pushBody();
}catch(Exception e){
  e.printStackTrace();
}finally{
  try{
   if(os != null){
    os.close();
    os = null;
   }
   if(is != null){
    is.close();
    is = null;
   }
  }catch(Exception e){
   e.printStackTrace();
  }
}
%>

猜你喜欢

转载自nidexuanzecjy-2014.iteye.com/blog/2292878