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

📄 upload2.jsp

📁 Java Web开发详解.书中例子的源代码(JSPlesson)
💻 JSP
字号:
<%@ page contentType="text/html; charset=GBK" %>
<%@ page import="java.util.List,java.util.Iterator"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="javax.naming.*,java.sql.*,javax.sql.DataSource"%>
<%@ page import="java.io.File"%>

<html>
    <head><title>upload2</title></head>
    <body>
    <%
        DiskFileUpload dfu=new DiskFileUpload();
        //设置上传数据的最大大小为10M。
        dfu.setSizeMax(0xA00000);

        //设置内存缓冲区的阀值为512K。
        dfu.setSizeThreshold(0x80000);

        //设置临时存储文件的目录为E:\fileupload。
        dfu.setRepositoryPath("E:\\fileupload");

        //得到FileItem对象的列表。
        List fileItems=dfu.parseRequest(request);
        Iterator it = fileItems.iterator();

        Context ctx=new InitialContext();
        DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/bookstore");
        Connection conn=ds.getConnection();
        PreparedStatement pstmt=conn.prepareStatement("insert into uploadfile(filename,filesize,data) values(?,?,?)");

        //依次处理每个上传的文件
        while (it.hasNext())
        {
            FileItem item = (FileItem) it.next();
            //判断是否是文件域的表单信息
            if (!item.isFormField())
            {
                String name = item.getName();
                //如果浏览器传送的文件名是全路径名,则取出文件名。
                int index=name.lastIndexOf(File.separator);
                if(index>0)
                    name=name.substring(index+1,name.length());

                long size = item.getSize();
                if((name==null || name.equals("")) && size==0)
                    continue;
                pstmt.setString(1,name);
                pstmt.setInt(2,(int)size);
                pstmt.setBinaryStream(3,item.getInputStream(),(int)size);
                pstmt.executeUpdate();
            }
        }
        if(pstmt!=null)
        {
            pstmt.close();
            pstmt=null;
        }
        if(conn!=null)
        {
            conn.close();
            conn=null;
        }
        out.println("上传成功!");
    %>
    </body>
</html>

⌨️ 快捷键说明

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