在开发的过程当中,经常遇到用文件上传的方式批量处理数据的方式,以前碰到的情况是先将文件保存到本地的临时文件,然后用poi的方式来进行处理,但是实际上,操作过程只是简单的读取操作,所以就不用那么复杂,下面记录了用servlet的javax.servlet.http.Part包的方式来处理这个功能。代码如下:

Part part=request.getPart("标签name");
         String filename=getFileName(part.getHeader("content-disposition") );
         Boolean resultCode = true;
         StringBuffer result=new StringBuffer();
         //校验
         if(StringHelper.isEmpty(filename)){
             result.append("请上传文件");
             resultCode = false;
         }else if(!filename.endsWith("csv")){
             result.append("上传文件只支持csv");
             resultCode = false;
         }
         if(resultCode){
             BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream())); 
             String line=null; 
             boolean isFirst=true;
             while ((line = reader.readLine()) != null) { 
                    if(!isFirst){
                        result.append(line).append(",");
                    }else{
                     isFirst=false; 
                    }
             } 
             if(0<result.length()){
                 result=result.delete(result.length()-1, result.length());
             }
         } 
         response.setContentType("text/html;charset=UTF-8");
         response.getWriter().print("<script type='text/javascript'>parent.callBack('"+result.toString()+"','"+resultCode+"');</script>");
         response.getWriter().close();
         return;

 

 private String getFileName(String header) { 
          if(!StringHelper.isEmpty(header)){
               String[] tempArr1 = header.split(";");
               String[] tempArr2 = tempArr1[2].split("="); 
               String fileName = tempArr2[1].substring(tempArr2[1].lastIndexOf("\\")+1).replaceAll("\"", "");
               return fileName;
          }else{
              return "";
          }
     }