⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 downloadservlet.java

📁 Java.Web开发详解.书中例子的源代码
💻 JAVA
字号:
package org.sunxin.lesson.jsp.ch22;

import java.io.*;
import java.sql.*;
import javax.naming.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.*;

public class DownloadServlet extends HttpServlet
{
    private DataSource ds=null;

    public void init() throws ServletException
    {
        try
        {
            Context ctx = new InitialContext();
            ds = (DataSource) ctx.lookup("java:comp/env/jdbc/bookstore");
        }
        catch (NamingException ex)
        {
            System.err.println(ex);
        }
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
        ServletException, IOException
    {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        String strId = request.getParameter("id");
        if (null == strId || strId.equals(""))
        {
            return;
        }
        File file=null;
        InputStream is=null;
        String fileName=null;
        int fileSize=0;

        //对从硬盘上下载文件进行处理。
        if(strId.equals("111"))
        {
            file=new File("D:\\tomcat5.exe");
            is=new FileInputStream(file);
            fileName=file.getName();
            fileSize=(int)file.length();
        }
        //对从数据库中下载文件进行处理。
        else
        {
            int id=Integer.parseInt(strId);
            try
            {
                conn = ds.getConnection();
                pstmt = conn.prepareStatement(
                    "select * from uploadfile where id=?");
                pstmt.setInt(1,id);
                rs = pstmt.executeQuery();
                if(rs.next())
                {
                    fileName=rs.getString("filename");
                    fileSize=rs.getInt("filesize");
                    is=rs.getBinaryStream("data");
                }
                else
                {
                    response.setContentType("text/html;charset=gb2312");
                    PrintWriter out=response.getWriter();
                    out.print("没有找到要下载的文件,请联系");
                    out.println("<a href=\"mailto:admin@sunxin.org\">管理员</a>");
                    out.close();
                    return;
                }
            }
            catch(SQLException e)
            {
                System.err.println(e);
            }
        }
        fileName=toUTF8String(fileName);
        //设置下载文件使用的报头域。
        response.setContentType("application/x-msdownload");
        String str = "attachment; filename="+fileName;
        response.setHeader("Content-Disposition", str);
        response.setContentLength(fileSize);

        //得到响应对象的输出流,用于向客户端输出二进制数据。
        ServletOutputStream sos=response.getOutputStream();
        byte[] data = new byte[2048];
        int len = 0;
        while((len=is.read(data)) >0)
        {
            sos.write(data,0,len); //向浏览器输出文件数据
        }
        is.close(); //关闭输入流
        sos.close();//关闭输出流
        if(rs!=null)
        {
            try
            {
                rs.close();
            }
            catch(SQLException e)
            {
                System.err.println(e);
            }
            rs=null;
        }
        if(pstmt!=null)
        {
            try
            {
                pstmt.close();
            }
            catch(SQLException e)
            {
                System.err.println(e);
            }
            pstmt=null;
        }
        if(conn!=null)
        {
            try
            {
                conn.close();
            }
            catch(SQLException e)
            {
                System.err.println(e);
            }
            conn=null;
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws
        ServletException, IOException
    {
        doGet(request, response);
    }

    public static String toUTF8String(String str)
    {
        StringBuffer sb = new StringBuffer();
        int len=str.length();

        for (int i=0;i<len;i++)
        {
            char c=str.charAt(i);
            if (c >= 0 && c <= 255)
            {
                sb.append(c);
            }
            else
            {
                byte[] b;
                try
                {
                    b = Character.toString(c).getBytes("UTF-8");
                }
                catch (UnsupportedEncodingException ex)
                {
                    System.err.println(ex);
                    b = null;
                }
                for (int j = 0; j < b.length; j++)
                {
                    int k = b[j];
                    if(k<0)
                    {
                        k &= 255;
                    }
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -