1. 程式人生 > >zlxdream815的專欄

zlxdream815的專欄

 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  Iterator<String> it = multipartRequest.getFileNames();
  while(it.hasNext()){
   CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile( it.next() );
   
     //判斷檔案是否為空,如果為空不執行下面的步驟
     if(file.getFileItem().getName()!=null && "".equals(file.getFileItem().getName())){
      InputStream stream = file.getInputStream();// 把檔案讀入
      String filePath = request.getRealPath(newpathname);//取系統當前路徑
      File file1 = new File(filePath);//添加了自動建立目錄的功能
      ((File) file1).mkdir();  
      newfileName = getTimeString()+  file.getFileItem().getName().substring(file.getFileItem().getName().lastIndexOf('.'));
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      OutputStream bos = new FileOutputStream(filePath + "/"+ newfileName);
      newpathname=filePath+"/"+newfileName;
      int bytesRead = 0;
      byte[] buffer = new byte[8192];
      while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
       bos.write(buffer, 0, bytesRead);// 將檔案寫入伺服器
      }
      bos.close();
      stream.close();
     }
   }
  }
  catch(FileNotFoundException e) {
      e.printStackTrace();
     } catch (IOException e) {
      e.printStackTrace();
     }