Java common-fileupload 文件上传

学struts2时做文件上传,使用apache common-fileupload模块,在struts中就是做不通,在servlet中试了一下,居然没有问题,搞得头大了,以后学习深入了在慢慢研究,怎么在struts中使用这个模块吧,估计是拦截器的问题。

protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
 

        
        boolean isMultipart=ServletFileUpload.isMultipartContent(request);
        if(isMultipart){
            DiskFileItemFactory factory=new DiskFileItemFactory();
            ServletContext servletContext=this.getServletConfig().getServletContext();
            File repository=(File)servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            //如果大小超过这个值,则直接保存到硬盘临时目录中
            factory.setSizeThreshold(2097152);
            ServletFileUpload upload = new ServletFileUpload(factory);
            //上传的文件总大小加起来不能超过该值
            upload.setSizeMax(1048576);
            try {
                List<FileItem> items=upload.parseRequest(request);
                Iterator<FileItem> it = items.iterator();
                while(it.hasNext()){
                    FileItem item=it.next();
                    if(!item.isFormField()){
                    //如果有多个上传标签,允许有空白的上传域
                        if(item.getSize()<=0)
                            continue;
                        String filename=item.getName();
                        item.write(new File(repository, filename));
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }


你可能感兴趣的:(Java common-fileupload 文件上传)