JSP 는 Common FileUpload 구성 요 소 를 사용 하여 파일 업로드 및 업로드 형식 인 스 턴 스 코드 제한

1.comons-fileupload-1.3.3.jar 를 웹 애플 리 케 이 션 의 lib 폴 더 에 복사 하여 WebRoot 디 렉 터 리 에 limit.jsp 페이지 를 만 들 고 이 페이지 에 파일 도 메 인 폼 을 추가 합 니 다.형식 을 설정 합 니 다.    multipart/form-data。코드 는 다음 과 같 습 니 다:

<body>
  <h2>      </h2>
  <form action="LimitFile" name="one" enctype="multipart/form-data" method="post">
        rar  :
    <input type="file" name="fileupload" value="upload" /> 
    <input type="submit" value="  "> <input type="reset" value="  ">
  </form>
 </body> 
상기 코드 지정 제출 후 요청 을 LimitFile 처리 에 제출 합 니 다.LimitFile(Servlet)은 업로드 파일 을 처리 하고 파일 형식 이 일치 하 는 지 판단 하여 업로드 결 과 를 표시 합 니 다.
2.LimitFile 이라는 Servlet 를 만 들 고 doPost()방법 에서 구현 코드 를 작성 합 니 다.다음 과 같 습 니 다.

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String uploadpath = "";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    //                         ,             。
    factory.setSizeThreshold(30 * 1024);
    //    setSizeThreshold()               ,          。
    factory.setRepository(factory.getRepository());
    ServletFileUpload upload = new ServletFileUpload(factory);
    List list = null;
    try{
      list = upload.parseRequest(request);
      String[] limit = new String[]{".jpg", ".gif", ".png", ".bmp"};
      //         
      SuffixFileFilter filter = new SuffixFileFilter(limit);
      //  SuffixFileFilter  
      Iterator iterator = list.iterator();
      while(iterator.hasNext()){
        FileItem item =(FileItem)iterator.next();
        if(!item.isFormField()){
          String filePath = item.getName();
          if(filePath != null){
            File filename= new File(filePath);
            File uploadFile = new File(request.getSession().getServletContext().getRealPath("/") + "upload");
            uploadpath = uploadFile.getAbsolutePath()+File.pathSeparator + uploadpath;
            //         ";" ,     
            uploadpath = uploadpath.substring(0, uploadpath.length()-1);
            File saveFile = new File(uploadpath,filename.getName());
            boolean flag = filter.accept(saveFile);
            if(flag){
              out.print("         ");
              break;
            }else{
              try {
                item.write(saveFile);
                out.print("      ");
              } catch (Exception e) {
                out.print("       ");
                e.printStackTrace();
              }
            }
          }
        }
      }
    }catch(FileUploadException e){
      e.printStackTrace();
    }
  }
이 코드 는 바이트 문자열 배열 limit 에서 업로드 할 수 없 는 파일 형식 을 정의 한 다음 이 배열 을 Suffix FileFilter 류 에 전달 하 는 구조 함수 입 니 다.이 종류의 accept()방법 을 통 해 현재 업로드 한 파일 이 조건 에 부합 되 는 지 검증 합 니 다.마지막 으로 파일 을 항목 의 upload 디 렉 터 리 에 저장 합 니 다.
총결산
위 에서 말 한 것 은 소 편 이 소개 한 JSP 가 Common FileUpload 구성 요 소 를 사용 하여 파일 업로드 및 업로드 형식 인 스 턴 스 코드 를 제한 하 는 것 입 니 다.여러분 에 게 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 저 에 게 메 시 지 를 남 겨 주세요.소 편 은 제때에 답 해 드 리 겠 습 니 다!

좋은 웹페이지 즐겨찾기