您的位置:首页 > 运维架构 > Tomcat

文件上传组件的应用

2008-04-22 20:28 417 查看
 注册页面的逻辑处理bean:doReg.java
  其中包括apache上传组件1.2.1的应用

 package huc.blog.servlet;




import huc.blog.bean.User;


import huc.blog.op.UserOp;




import java.io.File;


import java.io.IOException;


import java.util.Date;


import java.text.SimpleDateFormat;


import java.util.List;




import javax.servlet.ServletException;


import javax.servlet.http.HttpServlet;


import javax.servlet.http.HttpServletRequest;


import javax.servlet.http.HttpServletResponse;




import org.apache.commons.fileupload.FileItem;


import org.apache.commons.fileupload.FileUploadException;


import org.apache.commons.fileupload.disk.DiskFileItemFactory;


import org.apache.commons.fileupload.servlet.ServletFileUpload;






public class DoReg extends HttpServlet ...{






    /** *//**


     * 


     */


    private static final long serialVersionUID = 1L;




    @Override


    protected void doGet(HttpServletRequest req, HttpServletResponse resp)




            throws ServletException, IOException ...{


        doPost(req,resp);


    }




    @Override


    protected void doPost(HttpServletRequest req, HttpServletResponse resp)




            throws ServletException, IOException ...{


        SimpleDateFormat f=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        User user=new User();


        //设置保存上传文件的目录


        String uploadDir=getServletContext().getRealPath("/upload");




        if(uploadDir==null)...{


            System.out.println("该目录无法访问!");


            return;


        }


        


        File fileUploadDir=new File(uploadDir);


        




        if(!fileUploadDir.exists())...{




            if(!fileUploadDir.mkdir())...{


                System.out.println("无法创建目录!");


                return;


            }


        }


        


         //RequestContext requestContext = new ServletRequestContext(req);


        //判断表单中是否为multipart/form-data类型的数据,非则终止




        if(!ServletFileUpload.isMultipartContent(req))...{


            System.out.println("不能处理非multipart/form-data类型的数据!");


            return;


        }


        


        //创建DiskFileItemFactory对象,并进行一些设置


        DiskFileItemFactory factory = new DiskFileItemFactory();


        //设置直接能够存储的最大文件量,超出后采用临时文件缓存


        factory.setSizeThreshold(1024*1024);//以字节为单位




        /**//*Sets the directory used to temporarily store files that 


         *    are larger than the configured size threshold.


         *    默认为tomcat的安装目录 emp下


         */


        //factory.setRepository(java.io.File repository);


        


        ServletFileUpload upload = new ServletFileUpload(factory);


        //设置最多上传的数据量


        upload.setSizeMax(1024*1024*10);




        /** *//**


         * Specifies the character encoding to be used 


         * when reading the headers of individual part. 


         * When not specified, or null, the request encoding is used. 


         * If that is also not specified, or null, the platform default encoding is used. 


         */


        //upload.setHeaderEncoding("UTF-8");


        


        List<?> items=null;


        //得到表单字段的集合




        try...{


            


             items = upload.parseRequest(req);


             




        }catch(FileUploadException e)...{


            e.printStackTrace();


        }




        for(Object item:items)...{


            


            FileItem fileItem=(FileItem)item;


            //Determines whether or not a FileItem instance represents a simple form field. 




            if(fileItem.isFormField())...{


                


                // Returns the contents of the file item as a String, using the specified encoding.


                String content=fileItem.getString("UTF-8");


                String fieldName=fileItem.getFieldName();


                




                if(fieldName.equals("userName"))...{


                    user.setUserName(content);




                }else if(fieldName.equals("nickName"))...{


                    user.setNickName(content);




                }else if(fieldName.equals("userPass"))...{


                    user.setUserPass(content);




                }else if(fieldName.equals("email"))...{


                    user.setEmail(content);




                }else if(fieldName.equals("city"))...{


                    user.setCity(content);




                }else if(fieldName.equals("spaceName"))...{


                    user.setSpaceName(content);


                }    




            }else...{


                //Returns the original filename in the client's filesystem, 


                //as provided by the browser (or other client software).


                String source=fileItem.getName();


                


                //如果没有选择文件,则不进行处理




                if(source.trim().equals(""))...{


                    continue;


                }


                


                //得到上传的文件名


                int pos=source.lastIndexOf("/");


                String fileName=source.substring(pos+1);


                File file=new File(uploadDir,fileName);


                


                //write an uploaded item to disk




                try ...{


                    fileItem.write(file);




                } catch (Exception e) ...{


                    e.printStackTrace();




                }finally...{


                    //Deletes the underlying(潜在的)storage for a file item, 


                    //including deleting any associated temporary disk file


                    fileItem.delete();


                }


            }


        }


        Date date=new Date();


        user.setRegDate(f.format(date));


        user.setUpdateTime(f.format(date));


        


        UserOp userOp=new UserOp();


        




        if(!userOp.checkNotExist(user))...{


            String msg="该用户已存在,请重新填写!";


            req.setAttribute("msg",msg);


            req.getRequestDispatcher("../reg.jsp").forward(req,resp);


            return;


        }




        if(userOp.add(user))...{


            req.setAttribute("info", "success");


            req.getRequestDispatcher("../reginfo.jsp").forward(req, resp);




        }else...{


            req.setAttribute("info","failed");


            req.getRequestDispatcher("../reginfo.jsp").forward(req, resp);


        }


    }


    


}



 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息