fileUpload文件上传

1.Apache-fileUpload.jar引入
2.jsp页面
<body>
    <form action="../fileup01.do" 
        method="post" enctype="multipart/form-data">
        <!--enctype="multipart/form-data" -->
        用户名:<input type="text" name="username" /><br />
         文件:<input type="file"    name="photo" /><br> 
        兴趣:<input type="checkbox" name="interest" value="足球" />足球
            <input type="checkbox" name="interest" value="篮球" />篮球
            <input type="checkbox" name="interest" value="羽毛球" />羽毛球
            <input type="checkbox" name="interest" value="排球" />拍球
        <br>
         <input type="submit" value="提交" />
    </form>
</body>

3.Servlet
@WebServlet("/fileupload01")
public class FileServlet01 extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileServlet01() {
        super();
    }
    
    protected void file(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        boolean isMulipart=ServletFileUpload.isMultipartContent(request);
        System.out.println("FileServlet01.java file()");
        System.out.println(isMulipart);
        try {
            if(isMulipart){
                ServletFileUpload upload=new ServletFileUpload();
                FileItemIterator iter=upload.getItemIterator(request);
                InputStream is=null;
                //FileOutputStream fos=null;
                while(iter.hasNext()){
                    FileItemStream fis=iter.next();
                    is=fis.openStream();
                    if(fis.isFormField()){
                        System.out.println(fis.getFieldName()+":"+Streams.asString(is,"UTF-8"));
                    }else{
                        System.out.println(fis.getFieldName()+":"+fis.getName());
                        /*String path=request.getSession().getServletContext().getRealPath("/upload");
                        path=path+"/"+fis.getName();
                        System.out.println("path="+path);
                        fos=new FileOutputStream(path);
                        byte[] buf=new byte[1024];
                        int len=0;
                        while((len=is.read(buf))>0){
                            fos.write(buf, 0, len);
                        }*/
                    }
                }
                
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }/*finally{
            if(is!=null) is.close();
            if(fos!=null) fos.close();
        }*/
        response.sendRedirect("fileupload/fileupload01.jsp");
    }

    protected void file01(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username=request.getParameter("username");
        System.out.println("username="+username);
        InputStream is=null;
        FileOutputStream fos=null;
        boolean isMulipart=ServletFileUpload.isMultipartContent(request);
        System.out.println(isMulipart);
        try {
            if(isMulipart){
                ServletFileUpload upload=new ServletFileUpload();
                FileItemIterator iter=upload.getItemIterator(request);
                while(iter.hasNext()){
                    FileItemStream fis=iter.next();
                    is=fis.openStream();
                    if(fis.isFormField()){
                        System.out.println(fis.getFieldName()+":"+Streams.asString(is));
                    }else{
                        System.out.println(fis.getFieldName()+":"+fis.getName());
                        String path=request.getSession().getServletContext().getRealPath("/upload");
                        path=path+"/"+fis.getName();
                        System.out.println("path="+path);
                        fos=new FileOutputStream(path);
                        byte[] buf=new byte[1024];
                        int len=0;
                        while((len=is.read(buf))>0){
                            fos.write(buf, 0, len);
                        }
                    }
                }
                
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }finally{
            if(is!=null) is.close();
            if(fos!=null) fos.close();
        }
        response.sendRedirect("fileupload/fileupload01.jsp");
    }
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
    
    protected void file02(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if(ServletFileUpload.isMultipartContent(request)){
            
            request=new MultipartRequestWrapper(request);
        }
        String username=request.getParameter("username");
        System.out.println(username);
        
        String[] interest=request.getParameterValues("interest");
        for(String str:interest)
            System.out.println(str);
        response.sendRedirect("fileupload/fileupload01.jsp");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        //file(request,response);
        //file01(request,response);
        file02(request,response);
        
    }

}

4.ServletWrapper
public class MultipartRequestWrapper extends HttpServletRequestWrapper {

    Map<String,String[]> params=new HashMap<String,String[]>();
    public static final String PATH="D:\\Program Files\\apache-tomcat-7.0.42\\wtpwebapps\\Apache\\upload\\";
    
    public MultipartRequestWrapper(HttpServletRequest request) {
        super(request);
        setParams(request);
    }

    private void setParams(HttpServletRequest request) {
        System.out.println("MultipartRequestWrapper.java setParams()");
        try {
            boolean ismul=ServletFileUpload.isMultipartContent(request);
            if(ismul){
                ServletFileUpload upload=new ServletFileUpload();
                //upload.setHeaderEncoding("UTF-8");
                FileItemIterator iter=upload.getItemIterator(request);
                InputStream is=null;
                while(iter.hasNext()){
                    FileItemStream fis=iter.next();
                    is=fis.openStream();
                    if(fis.isFormField()){
                        //params.put(fis.getFieldName(),new String[]{Streams.asString(is)});
                        setFormParam(fis.getFieldName(),is);
                    }else{
                        if(is.available()>0){//输入流中有数据才上传
                            //对于IE浏览器会获取到文件绝对路径,此时需要分离出文件名
                            String fname=FilenameUtils.getName(fis.getName());
                            System.out.println("上传文件名="+fname);
                            Streams.copy(is, new FileOutputStream(PATH+fname), true);
                            params.put(fis.getFieldName(),new String[]{fname});
                        }
                    }
                }
            }else{
                params=request.getParameterMap();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    

    private void setFormParam(String fieldName, InputStream is) throws IOException {
        System.out.println("MultipartRequestWrapper.setFormParam() set:"+fieldName);
        if(params.containsKey(fieldName)){
            String[] values=params.get(fieldName);
            values=Arrays.copyOf(values,values.length+1);
            values[values.length-1]=Streams.asString(is,"utf-8");
            params.put(fieldName,values);    
        }else{
            params.put(fieldName,new String[]{Streams.asString(is,"utf-8")});
        }
        
    }

    public Map<String, String[]> getParams() {
        return params;
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        return super.getParameterMap();
    }
    
    @Override
    public String getParameter(String name) {
        String[] values=params.get(name);
        if(values!=null){
            return values[0];
        }
        return null;
    }
    
    @Override
    public String[] getParameterValues(String name) {
        String[] values=params.get(name);
        if(values!=null){
            return values;
        }
        return null;
    }
}


你可能感兴趣的:(fileUpload文件上传)