java web中servlet实现post方法上传多文件数据接收

最近一直看java web如何实现sverlet接收post一次上传的多文件数据。目前找到亲测靠谱的实现方法,已经在项目中跑过可用。
需要用到的jar包:
commons-fileupload-1.3.2.jar(http://commons.apache.org/proper/commons-fileupload/download_fileupload.cgi)
commons-io-2.5.jar(http://commons.apache.org/io/download_io.cgi)
代码:
public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	request.setCharacterEncoding("utf-8");//防止中文名乱码  
        int sizeThreshold=1024*6; //缓存区大小  
        String basePath = this.getServletContext().getRealPath("/upload/");
        System.out.println(basePath);
        File repository = new File(basePath); //缓存区目录  
        long sizeMax = 1024 * 1024 * 2;//设置文件的大小为2M  
        final String allowExtNames = "jpg,gif,bmp,rar,rar,txt,docx,png";  
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();  
        diskFileItemFactory.setRepository(repository);  
        diskFileItemFactory.setSizeThreshold(sizeThreshold);  
        ServletFileUpload servletFileUpload=new ServletFileUpload(diskFileItemFactory);  
        servletFileUpload.setSizeMax(sizeMax);  
          
        List<FileItem> fileItems = null;  
        try{  
            fileItems = servletFileUpload.parseRequest(request);  
              
            for(FileItem fileItem:fileItems){  
                long size=0;  
                String filePath = fileItem.getName(); 
                System.out.println(filePath);  
                if(filePath==null || filePath.trim().length()==0)  
                    continue;  
                String fileName=filePath.substring(filePath.lastIndexOf(File.separator)+1);   
                String extName=filePath.substring(filePath.lastIndexOf(".")+1);   
                if(allowExtNames.indexOf(extName)!=-1)  
                {  
                    try {  
                        fileItem.write(new File(basePath+File.separator+fileName));  
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  
                }  
                else{  
                    throw new FileUploadException("file type is not allowed");  
                }  
            }  
        }catch(FileSizeLimitExceededException e){  
            System.out.println("file size is not allowed");  
        }catch(FileUploadException e1){  
            e1.printStackTrace();  
        }  
	response.setContentType("text/html");
	response.setCharacterEncoding("utf-8");
	PrintWriter out = response.getWriter();
	out.println("this is Post method");
	out.flush();
	out.close();
}

项目结构:

服务器一次post上传存储结果:





  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值