Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2295628
  • 博文数量: 252
  • 博客积分: 5472
  • 博客等级: 大校
  • 技术积分: 3107
  • 用 户 组: 普通用户
  • 注册时间: 2011-09-17 18:39
文章分类

全部博文(252)

文章存档

2012年(96)

2011年(156)

分类: 系统运维

2011-12-17 16:59:33

超链接下载会暴露文件的真实位置 而且 只能下载存放在Web应用程序所在的目录下
 
我们可以利用程序编码实现下载 可以增加安全访问控制 对经过认证的用户提供下载 从任意位置提供下载的数据 可以将下载的文件存放在Web应用程序以外的目录中 也可以将文件保存到数据库中
 
利用程序下载 只要按照如下的方式设置三个报头域即可
  1. Content-Type:application/x-msdownload
  2. Content-Disposition:attachment;filaname=downloadfile
  3. Content-Length:filesize

浏览器在接收在上述的报头信息后 就会弹出文件下载的对话框 让你将文件保存到本地硬盘

 

1   index.jsp

 

  1. <%@ page contentType="text/html; charset=GBK" %>
  2. <%@ page import="javax.naming.*,java.sql.*,javax.sql.DataSource"%>

  3. <html>
  4.     <head><title>index</title></head>
  5.     <body>
  6.         点击下面的链接下载文件<p>
  7.         <a href="download.jsp?id=111">tomcat6.exe</a><br>
  8.     <%
  9.         Context ctx=new InitialContext();
  10.         DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/bookstore");
  11.         Connection conn=ds.getConnection();
  12.         Statement stmt=conn.createStatement();
  13.         ResultSet rs=stmt.executeQuery("select id,filename from uploadfile");
  14.         while(rs.next())
  15.         {
  16.     %>
  17.     <a href="download.jsp?id=<%=rs.getInt(1)%>"><%=rs.getString(2) %></a><br>
  18.     <%
  19.         }
  20.     %>
  21.     </body>
  22. </html>

 

 

2 DownloadServlet.java

 

  1. package org.sunxin.ch20.servlet;

  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.PrintWriter;
  7. import java.io.UnsupportedEncodingException;
  8. import java.sql.Connection;
  9. import java.sql.PreparedStatement;
  10. import java.sql.ResultSet;
  11. import java.sql.SQLException;

  12. import javax.naming.Context;
  13. import javax.naming.InitialContext;
  14. import javax.naming.NamingException;
  15. import javax.servlet.ServletException;
  16. import javax.servlet.ServletOutputStream;
  17. import javax.servlet.http.HttpServlet;
  18. import javax.servlet.http.HttpServletRequest;
  19. import javax.servlet.http.HttpServletResponse;
  20. import javax.sql.DataSource;

  21. public class DownloadServlet extends HttpServlet
  22. {
  23.     private DataSource ds=null;

  24.     public void init() throws ServletException
  25.     {
  26.         try
  27.         {
  28.             Context ctx = new InitialContext();
  29.             ds = (DataSource) ctx.lookup("java:comp/env/jdbc/bookstore");
  30.         }
  31.         catch (NamingException ex)
  32.         {
  33.             System.err.println(ex);
  34.         }
  35.     }

  36.     public void doGet(HttpServletRequest request, HttpServletResponse response) throws
  37.         ServletException, IOException
  38.     {
  39.         Connection conn = null;
  40.         PreparedStatement pstmt = null;
  41.         ResultSet rs = null;

  42.         String strId = request.getParameter("id");
  43.         if (null == strId || strId.equals(""))
  44.         {
  45.             return;
  46.         }
  47.         File file=null;
  48.         InputStream is=null;
  49.         String fileName=null;
  50.         int fileSize=0;

  51.         //对从硬盘上下载文件进行处理。

  52.         if(strId.equals("111"))
  53.         {
  54.             file=new File("D:\\tomcat6.exe");
  55.             is=new FileInputStream(file);
  56.             fileName=file.getName();
  57.             fileSize=(int)file.length();
  58.         }
  59.         //对从数据库中下载文件进行处理。

  60.         else
  61.         {
  62.             int id=Integer.parseInt(strId);
  63.             try
  64.             {
  65.                 conn = ds.getConnection();
  66.                 pstmt = conn.prepareStatement(
  67.                     "select * from uploadfile where id=?");
  68.                 pstmt.setInt(1,id);
  69.                 rs = pstmt.executeQuery();
  70.                 if(rs.next())
  71.                 {
  72.                     fileName=rs.getString("filename");
  73.                     fileSize=rs.getInt("filesize");
  74.                     is=rs.getBinaryStream("data");
  75.                 }
  76.                 else
  77.                 {
  78.                     response.setContentType("text/html;charset=gb2312");
  79.                     PrintWriter out=response.getWriter();
  80.                     out.print("没有找到要下载的文件,请联系");
  81.                     out.println("管理员");
  82.                     out.close();
  83.                     return;
  84.                 }
  85.             }
  86.             catch(SQLException e)
  87.             {
  88.                 System.err.println(e);
  89.             }
  90.         }
  91.         fileName=toUTF8String(fileName);
  92.         //设置下载文件使用的报头域。

  93.         response.setContentType("application/x-msdownload");
  94.         String str = "attachment; filename="+fileName;
  95.         response.setHeader("Content-Disposition", str);
  96.         response.setContentLength(fileSize);

  97.         //得到响应对象的输出流,用于向客户端输出二进制数据。

  98.         ServletOutputStream sos=response.getOutputStream();
  99.         byte[] data = new byte[2048];
  100.         int len = 0;
  101.         while((len=is.read(data)) >0)
  102.         {
  103.             sos.write(data,0,len); //向浏览器输出文件数据

  104.         }
  105.         is.close(); //关闭输入流

  106.         sos.close();//关闭输出流

  107.         if(rs!=null)
  108.         {
  109.             try
  110.             {
  111.                 rs.close();
  112.             }
  113.             catch(SQLException e)
  114.             {
  115.                 System.err.println(e);
  116.             }
  117.             rs=null;
  118.         }
  119.         if(pstmt!=null)
  120.         {
  121.             try
  122.             {
  123.                 pstmt.close();
  124.             }
  125.             catch(SQLException e)
  126.             {
  127.                 System.err.println(e);
  128.             }
  129.             pstmt=null;
  130.         }
  131.         if(conn!=null)
  132.         {
  133.             try
  134.             {
  135.                 conn.close();
  136.             }
  137.             catch(SQLException e)
  138.             {
  139.                 System.err.println(e);
  140.             }
  141.             conn=null;
  142.         }
  143.     }

  144.     public void doPost(HttpServletRequest request, HttpServletResponse response) throws
  145.         ServletException, IOException
  146.     {
  147.         doGet(request, response);
  148.     }
  149.     public static String toUTF8String(String str)
  150.     {
  151.        StringBuffer sb = new StringBuffer();
  152.        int len=str.length();

  153.        for (int i=0;i<len;i++)
  154.        {
  155.             char c=str.charAt(i);
  156.            if (c >= 0 && c <= 255)
  157.            {
  158.                sb.append(c);
  159.            }
  160.            else
  161.            {
  162.                 byte[] b;
  163.                 try
  164.                 {
  165.                     b = Character.toString(c).getBytes("UTF-8");
  166.                 }
  167.                 catch (UnsupportedEncodingException ex)
  168.                 {
  169.                     System.err.println(ex);
  170.                     b = null;
  171.                 }
  172.                 for (int j = 0; j < b.length; j++)
  173.                 {
  174.                     int k = b[j];
  175.                     if(k<0)
  176.                     {
  177.                         k &= 255;
  178.                     }
  179.                     sb.append("%" + Integer.toHexString(k).toUpperCase());
  180.                 }
  181.             }
  182.         }
  183.         return sb.toString();
  184.     }
  185. }

 

3  解决中文文件名问题

从硬盘盒数据库中存储的文件数据如果下载的文件名中有中文名 浏览器保存的文件名将显示乱码

对下载的文件面按照UTF-8进行编码

在servlet中增加一个静态的字符编码转换方法toUTF8String()

阅读(3239) | 评论(0) | 转发(0) |
0

上一篇:文件上传

下一篇:给图片添加水印和文字

给主人留下些什么吧!~~