jsp文件下载另存为中文

来源:互联网 发布:迪普科技薪酬 知乎 编辑:程序博客网 时间:2024/04/29 22:50
Java代码  收藏代码
  1. <%@ page contentType="text/html;charset=gb2312"%>  
  2. <%@ page import="java.io.File"%>  
  3. <%@ page import="java.io.*"%>  
  4. <title>文档下载保存中转页面</title>  
  5. </head>  
  6. <!--  
  7.   *文件名:down_center.jsp  
  8.   *实现功能:服务器上保存的文件名为按上传时间命名的  
  9.                 下载时自动替换为中文文件名  
  10.   *遗留问题:无格式判断功能,有待开发  
  11.   *编写时间:2006-9-5  
  12.   *代码编写:郑兆童  
  13.   *最终修改时间:2006-9-5  
  14.   *最终修改内容:无  
  15. -->  
  16. <body>  
  17. <%  
  18. String root = getServletContext().getRealPath("/");      //得到网站绝对路径  
  19. //String filepath = "upload_file\\lwfile\\";                        //设置文件存放的相对路径(windows)  
  20. String filepath = "upload_file/lwfile/";                             //设置文件存放的相对路径(linux)  
  21. String fileName = request.getParameter("filename");    //得到文件名  
  22. String myName = "中文文档下载.doc";                              //文件改名  
  23.   
  24. out.print(root + filepath + fileName);  
  25.   
  26. // 设置响应头和下载保存的文件名  
  27. response.reset();  
  28. //response.setContentType("application/octet-stream");       //windows  
  29. //response.addHeader("Content-Disposition", "filename=\"" + myName + "\"");      //windows  
  30. response.setContentType("application/octet-stream; charset=GBK");     //linux  
  31.   
  32. response.addHeader("Content-Disposition""attachment; filename=\"" + new String(myName.getBytes("gb2312"),"iso8859-1") + "\"");      //linux  
  33.   
  34.   
  35. //新建文件输入输出流  
  36. OutputStream output = null;  
  37. FileInputStream fis = null;  
  38. try{  
  39.   //新建File对象  
  40.   File f = new File(root + filepath + fileName);  
  41.   //新建文件输入输出流对象  
  42.   output = response.getOutputStream();  
  43.   fis = new FileInputStream(f);  
  44.   //设置每次写入缓存大小  
  45.   byte[] b = new byte[(int)f.length()];  
  46.   //out.print(f.length());  
  47.   //把输出流写入客户端  
  48.   int i = 0;  
  49.   while((i = fis.read(b)) > 0){  
  50.     output.write(b, 0, i);  
  51.   }  
  52.   output.flush();  
  53. }  
  54. catch(Exception e){  
  55.   e.printStackTrace();  
  56. }  
  57. finally{  
  58.   if(fis != null){  
  59.     fis.close();  
  60.     fis = null;  
  61.   }  
  62.   if(output != null){  
  63.     output.close();  
  64.     output = null;  
  65.   }  
  66. }  
  67. %>  
  68. </body>  
  69. </html>  
0 0
原创粉丝点击