파일 업로드 구성 요 소 를 사용 하여 파일 업로드 기능 을 실현 합 니 다.

FileUpload 파일 업로드
fileUpload 는 apache 의 comons 구성 요소 가 제공 하 는 업로드 구성 요소 입 니 다.가장 중요 한 작업 은 request.getInpustream()을 분석 하 는 것 입 니 다.
fileUpload 구성 요 소 를 사용 하려 면 먼저 두 개의 jar 패 키 지 를 도입 해 야 합 니 다.
  • commons-fileUpload.jar
  • commons-io.jar
  •   fileUpload 의 핵심 클래스 는 DiskFileItemFactory,ServletFileUpload,FileItem 입 니 다.
    fileUpload 고정 절차 사용:
  • 공장 클래스 생 성:DiskFileItemFactory factory=new DiskFileItemFactory();
  • 해석 기 생 성:ServletFileUpload upload=new ServletFileUpload(factory);
  • 해상도 기 를 사용 하여 request 대상 을 분석 합 니 다.List list=upload.parseRequest(request);
  • 하나의 FileItem 대상 이 폼 항목 에 대응 합 니 다.FileItem 클래스 는 다음 과 같은 방법 이 있 습 니 다.
  • String getFieldName():폼 항목 의 name 속성 값 을 가 져 옵 니 다.
  • String getName():파일 필드 의 파일 이름 을 가 져 옵 니 다.일반 필드 라면 null
  • 로 돌아 갑 니 다.
  • String getString():필드 의 내용 을 가 져 옵 니 다.일반 필드 라면 value 값 입 니 다.파일 필드 라면 파일 내용 입 니 다.
  • String getContentType():텍스트/plain,image 와 같은 업 로드 된 파일 형식 을 가 져 옵 니 다.일반 필드 라면 null 로 돌아 갑 니 다.
  • long getSize():필드 내용 의 크기 를 가 져 옵 니 다.단 위 는 바이트 입 니 다.
  • boolean isFormField():일반 폼 필드 인지 판단 하고 true 로 돌아 가지 않 으 면 false 로 돌아 갑 니 다.
  • InputStream getInputStream():파일 내용 의 입력 흐름 을 가 져 옵 니 다.일반 필드 라면 value 값 의 입력 흐름 을 되 돌려 줍 니 다.
  • 전단 페이지
    
    <%@ page language="java" contentType="text/html; charset=utf-8"
     pageEncoding="utf-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Insert title here</title>
    </head>
    <body>
     <form action="uploadServlet" enctype="multipart/form-data" method="post">
     <input type="text" name="username">
     <input type="password" name="pwd">
     <input type="file" name="pic">
     <input type="submit">
    </form>
    </body>
    </html>
    UploadServlet
    
    package pers.zhang.servlet;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.List;
    import java.util.UUID;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    
    
    public class UploadServlet extends HttpServlet {
     
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     doPost(request, response);
     }
    
    
     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     DiskFileItemFactory factory=new DiskFileItemFactory();
     ServletFileUpload upload=new ServletFileUpload(factory);
     
     request.setCharacterEncoding("utf-8");
     //               
    // upload.setHeaderEncoding("utf-8");
     
     //              
     factory.setSizeThreshold(1024*1024*10);
     File uploadTemp=new File("e:\\uploadTemp");
     uploadTemp.mkdirs();
     factory.setRepository(uploadTemp);
     
     //          
     upload.setFileSizeMax(1024*1024*10);
     //            
     upload.setSizeMax(1024*1024*30);
     
     try {
     List<FileItem> list=upload.parseRequest(request);
     System.out.println(list);
     for (FileItem fileItem:list){
     if (!fileItem.isFormField()&&fileItem.getName()!=null&&!"".equals(fileItem.getName())){
      String filName=fileItem.getName();
      //  UUID        ,         
      String uuid= UUID.randomUUID().toString();
      //       
      String suffix=filName.substring(filName.lastIndexOf("."));
     
      //          ,         upload   。               ,    WEB-INF 
      String uploadPath=request.getSession().getServletContext().getRealPath("/upload");
     
      File file=new File(uploadPath);
      file.mkdirs();
      //       ,       ,       ,      
      fileItem.write(new File(uploadPath,uuid+suffix));
      
     }
     }
     } catch (Exception e) {
     e.printStackTrace();
     }
     }
    
    }
    테스트

    콘 솔 인쇄:
    [name=null, StoreLocation=e:\uploadTemp\upload_9e72474_16ddcccabe6__8000_00000000.tmp, size=5bytes, isFormField=true, FieldName=username, name=null, StoreLocation=e:\uploadTemp\upload_9e72474_16ddcccabe6__8000_00000001.tmp, size=6bytes, isFormField=true, FieldName=pwd, name=C:\Users\19798\Desktop\test.txt, StoreLocation=e:\uploadTemp\upload_9e72474_16ddcccabe6__8000_00000002.tmp, size=20bytes, isFormField=false, FieldName=pic]
    프로젝트 배치 경로 에서 upload 폴 더:

    fileUpload 구성 요 소 를 사용 하여 파일 업 로드 를 실현 합 니 다.위의 방법 외 에 도 주의해 야 할 것 은:
  • 파일 이름 중국어 난호 처리:servletFileUpload.setHeaderEncoding("utf-8")또는 request.setCharacterEncoding("utf-8");
  • 폼 일반 필드 중국어 난호 처리:new String(str.getBytes("iso-8859-1","utf-8");
  • 메모리 버퍼 의 크기 를 설정 합 니 다.기본 값 은 10KB:diskFileItemFactory.setSizeThreshold(1024*1024)입 니 다.
  • 임시 파일 디 렉 터 리 를 지정 합 니 다.단일 파일 의 크기 가 메모리 버퍼 를 초과 하면 이 디 렉 터 리 에 임시 적 으로 느 려 집 니 다.diskFileItemFactory.setRepository(file);
  • 단일 파일 크기 제한 을 설정 합 니 다.이 크기 를 초과 하 는 파일 이 있 으 면 FileUploadBase.FileSizeLimitExceed Exception:servletFileUpload.setFileSizeMax(10241024110)를 던 집 니 다.
  • 모든 파일 을 설정 합 니 다.즉,요청 크기 제한 입 니 다.파일 의 합계 가 이 크기 를 초과 하면 FileUploadBase.SizeLimit Exceed Exception:servletFileUpload.setSizeMax(1024102420)를 던 집 니 다.
  • UUID 를 이용 하여 위조 무 작위 문자열 을 파일 이름 으로 생 성하 여 중복 을 피 합 니 다:UUID.randomUUID().toString();
  • 파일 을 하드디스크 에 쓴다.작성 후 시스템 은 임시 파일 디 렉 터 리 에 있 는 이 파일 을 자동 으로 삭제 합 니 다:fileItem.write(new File(path,fileName);
  • 또한 임시 파일 디 렉 터 리 가 지정 되 지 않 으 면 시스템 의 기본 임시 파일 경 로 를 사용 합 니 다.System.getProperty("java.io.tmpdir")를 통 해 가 져 올 수 있 습 니 다.Tomcat 시스템 의 기본 임시 디 렉 터 리 는"/temp/"입 니 다.
    Apache 파일 업로드 구성 요 소 는 업 로드 된 데이터 의 각 필드 내용 을 분석 할 때 뒤에 데 이 터 를 추가 처리 할 수 있 도록 해 석 된 데 이 터 를 임시로 저장 해 야 합 니 다(디스크 의 특정 위치 에 저장 하거나 데이터 베 이 스 를 삽입).자바 가상 컴퓨터 가 기본적으로 사용 할 수 있 는 메모리 공간 이 제한 되 어 있 기 때문에 제한 을 초과 하면'자바.lang.OutOfmory Error'오류 가 발생 합 니 다.만약 에 업로드 한 파일 이 매우 크다 면,예 를 들 어 800 M 의 파일 은 메모리 에 이 파일 의 내용 을 임시로 저장 할 수 없고,아파 치 파일 업로드 구성 요 소 는 임시 파일 로 이 데 이 터 를 저장한다.그러나 업로드 한 파일 이 매우 작다 면,예 를 들 어 600 바이트 의 파일 은 메모리 에 직접 저장 하 는 것 이 더욱 좋 을 것 이다.
    이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

    좋은 웹페이지 즐겨찾기