downloadpage.jsp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  2. <%@ page import="java.io.FileInputStream"%>
  3. <%@ page import="java.io.File"%>
  4. <%@ page import="java.io.OutputStream"%>
  5. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  6. <html>
  7. <%
  8. //若使用字节流进行文件下载,应该首先清空一下out对象,默认是字符流
  9. out.clear();
  10. out = pageContext.pushBody();
  11. response.setContentType("application/force-download");
  12. String path=request.getParameter("path").replace("../..","D:/apache-tomcat-6.0.41/webapps/cetdz");
  13. System.out.println(path);
  14. String filename=java.net.URLDecoder.decode(request.getParameter("filename"),"UTF-8");
  15. //filename=path.substring(path.lastIndexOf("/")+1);
  16. System.out.println(filename);
  17. if (request.getHeader("user-agent").toLowerCase().contains("msie")) {
  18. // IE
  19. filename = java.net.URLEncoder.encode(filename, "UTF-8");
  20. } else {
  21. // 非IE
  22. filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
  23. }
  24. //filename=new String(filename.getBytes("UTF-8"),"ISO8859-1");
  25. //filename=path.substring(path.lastIndexOf("/")+1);
  26. //通过设置头标题来显示文件传送到前端浏览器的文件信息
  27. response.setHeader("Content-disposition","inline;filename="+filename);
  28. File file = new File(path);
  29. response.setHeader("Content_Length",String.valueOf(file.length()));
  30. FileInputStream input = null;
  31. OutputStream output = null;
  32. try{
  33. input = new FileInputStream(file);
  34. output = response.getOutputStream();
  35. byte size[] = new byte[1024];
  36. int length;
  37. while((length=input.read(size))!=-1){
  38. output.write(size);
  39. }
  40. }catch(Exception e){
  41. System.out.print(e.getMessage());
  42. }finally{
  43. try{
  44. input.close();
  45. output.flush();
  46. output.close();
  47. }catch(Exception ex){
  48. }
  49. }
  50. %>
  51. <script></script>
  52. <head>
  53. <title>My JSP 'index.jsp' starting page</title>
  54. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  55. <meta http-equiv="pragma" content="no-cache">
  56. <meta http-equiv="cache-control" content="no-cache">
  57. <meta http-equiv="expires" content="0">
  58. </head>
  59. <body>
  60. This is my JSP page. <br>
  61. </body>
  62. </html>