1. 程式人生 > >從request中獲取檔案流的兩種方式

從request中獲取檔案流的兩種方式

Collection<Part> parts = req.getParts();
for (Iterator<Part> iterator = parts.iterator(); iterator.hasNext();) {
    Part part = iterator.next();  
    System.out.println("-----型別名稱------->"+part.getName());
    System.out.println("-----型別------->"+part.getContentType());
    System.out.println("-----提交的型別名稱------->"+part.getSubmittedFileName());
    System.out.println("----流-------->"+part.getInputStream());
}

方法二: 從MultipartHttpServletRequest中獲取檔案資訊

//將當前上下文初始化給  CommonsMutipartResolver (多部分解析器)
CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                    request.getSession().getServletContext());
// 判斷是否是多資料段提交格式
 if (multipartResolver.isMultipart(request)) {
         MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
         Iterator<String> iter = multiRequest.getFileNames();
         logger.info("iter.hasNext(): "+iter.hasNext());
         Integer fileCount = 0;
         while (iter.hasNext()) {
                MultipartFile multipartFile = multiRequest.getFile(iter.next());
                String fileName = multipartFile.getOriginalFilename();
                logger.info("upload filename: " + fileName );
                if(fileName == null || fileName.trim().equals("")){
                      continue;
                }
                //20170207 針對IE環境下filename是整個檔案路徑的情況而做以下處理
                Integer index = fileName.lastIndexOf("\\");
                String newStr = "";
                 if(index>-1){
                       newStr = fileName.substring(index+1);
                  }else{
                       newStr = fileName;
                  }
                 if(!newStr.equals("")){
                        fileName = newStr;
                  }
                  logger.info("new filename: " + fileName );

                  if (multipartFile != null) {
                        HashMap<String,Object> result =  DispatchInterfaceUtil.uploadInputStream(multipartFile.getInputStream(),multipartFile.getSize(),fileName);
                  }
        }
}