반응형

파일 업로드

 

- 파일 업로드는 클라이언트에서 웹 서버로 파일을 전송하는 것을 말한다.
- 파일 업로드를 구현하기 위해 서블릿 3.0부터는 API가 제공된다.
- 실습은 서블릿 2.x에서 구현하던 방식을 사용한다.(파일 업로드 라이브러리를 사용)

 

실습준비
http://www.servlets.com/cos 접속
- Download에서 cos-26Dec2008.zip 파일 다운

 

압축해제 후 cos-26Dec2008\lib 폴더의 cos.jar파일을 복사하여 WEB-INF/lib폴더에 추가

 

파일전송을 위한 폼 태그 형식

<form name=”이름” method=”post” enctype=”multipart/form-data”>
     <input type=”file” name=”이름”>
</form> 

 

실습예제-업로드 폼

/WebContent/fileUpload/upload_form.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<title>파일 전송 폼</title>
</head>
<body>
    <form action="upload_process.jsp" method="post"
        enctype="multipart/form-data">
        글쓴이 : <input type="text" name="name">
        <p>
            제 &nbsp; 목 : <input type="text" name="title">
        <p>
            파일 선택 : <input type="file" name="uploadFile">
        <p>
            <input type="submit" value="전송">
    </form>
</body>
</html>
cs

 

요청결과

 

 

MultipartRequest 클래스
- MultipartRequest 클래스는 파일 업로드 기능을 담당하는 클래스이다.
- cos.jar 파일이 MultipartRequest 클래스를 제공

- 서블릿3.0규격 이하에서는 파일업로드를 위한 multipart클래스 기능을 구현하거나 별도의

  라이브러리를 사용해야 함.

 

cos라이브러리의 MultipartRequest 클래스의 메서드


파일 업로드를 위한 작업


- WebContent/fileUpload/upload 폴더 생성

 

- 파일을 저장하기 위한 디렉터리와 파일의 최대 크기 정의

 
 
 
String savePath = “/fileUpload/upload”;  //다운받는 경로 설정
int uploadFileSizeLomit = 5*1024*1024//파일 최대크기 5M로 제한
String encType=”UTF-8” //char인코딩 방식
cs

 

- 서버 상의 실제 경로 설정
 
 
ServletContext context = getServletContext();
String uploadFilePath = context.getRealPath(savePath);
cs

 

- MultipartRequest 클래스 객체 생성

 
 
 
 
 
 
 
 
MultipartRequest multi = new MultipartRequest(
            request,        //request 객체
            uploadFilePath,    //서버 상의 실제 데이터
            uploadFileSizeLimit, //최대 업로드 파일크기
            encType,        //인코딩 타입
            new DefaultFileRenamePolicy()
            );
 
cs

 

- 업로드 된 파일의 이름 얻기

 
 
 
String filename = multi.getFilesystemName(“uploadFile”);
//”uploadFile” 이름은 input 태그의 name과 동일한 이름을 사용한다.
 
cs

 

- 실제 업로드 된 파일이 저장될 위치(이클립스에서 사용하는 workspace안에 다음 경로)
.matadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\프로젝트명\upload

이클립스에서 JSP프로젝트를 실행하는 경우 퍼블리싱 이라는 기능이 동작함.

프로젝트 파일을 별도의 작업경로(위의 경로)에 복사한 후 처리(퍼블리싱 기능 해제 가능)

 

실습코드
/WebContent/fileUpload/upload_process.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.oreilly.servlet.MultipartRequest" %>
<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy" %>
<html>
<head><title>업로드 처리</title></head>
<body>
<%
    request.setCharacterEncoding("UTF-8");
    String savePath = "/fileUpload/upload";
    int uploadFileSizeLimit = 5 * 1024 * 1024;
    String encType = "UTF-8";
    
    ServletContext context = getServletContext();
    String uploadFilePath = context.getRealPath(savePath);
    System.out.println("서버상의 실제 디렉터리");
    System.out.println(uploadFilePath);
    try{
        MultipartRequest multi = new MultipartRequest(
                request,
                uploadFilePath,
                uploadFileSizeLimit,
                encType,
                new DefaultFileRenamePolicy());
        String fileName = multi.getFilesystemName("uploadFile");
        if(fileName == null){
            System.out.print("파일 업로드 실패");
        }
        else{
            out.println("<br> 글쓴이 : " + multi.getParameter("name"));
            out.println("<br> 제 &nbsp; 목 : " + multi.getParameter("title"));
            out.println("<br> 파일명 : " + fileName);
        }
    }catch(Exception e){
        System.out.print("예외 발생 : " + e);
        e.printStackTrace();
    }
%>
</body>
</html>
 
cs

 

파일업로드(클라이언트)

 

업로드 결과(파일이 만들어진 것은 서버의 경로)

 

다중 파일 전송(한번에 여러 개 파일 업로드)
- 폼 태그

 
 
 
 
 
 
<form action=”파일명” method=”post” enctype=”multipart/form-data”>
 1.파일 지정 : <input type=”file” name=“uploadFile01”> <br>
 2.파일 지정 : <input type=”file” name=“uploadFile02”> <br>
 3.파일 지정 : <input type=”file” name=“uploadFile03”> <br>
<input type=”submit” value=”전송”>
</form>
cs

 

MultipartRequest 객체의 getFileNames() 메서드를 사용하여 파일 이름을 얻는다.
이때 컬렉션의 Enumeration 클래스 사용한다.

 - Enumeration으로 파일 이름을 가져오기 위해서는 hasMoreElements()로 데이터가 있는지 확인한 후, nextElement()를 호출하여 해당 데이터를 가져오면서 위치를 한 칸씩 이동시키는 방식으로 모든 데이터를 검색할 수 있다.

 

사용 예)

 
 
 
 
 
 
 
 
 
Enumeration files = multi.getFileNames();
while (files.hasMoreElements()) {
    String file = (String) files.nextElement();
    //Enumeration으로 얻어온 파일 이름을 getFilesystemName()의 매개변수로 전달하여 
    //업로드된 파일 이름 가져오기
    String file_name = multi.getFilesystemName(file);
    //중복된 파일을 업로드할 경우 파일명 뒤에 번호를 자동으로 붙여 새로운 파일 이름을 제공한다.
    String ori_file_name = multi.getOriginalFileName(file);
}
cs

 

다중 파일업로드 실습
/WebContent/fileUpload/multiple_upload_form.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 
<html>
<head>
<title>다중 파일 업로드</title>
</head>
<body>
    <form action="multiple_upload_process.jsp" method="post" enctype="multipart/form-data">
        1. 파일 지정 : <input type="file" name="uploadFile01"> <br>
        2. 파일 지정 : <input type="file" name="uploadFile02"> <br>
        3. 파일 지정 : <input type="file" name="uploadFile03"> <br> <input
            type="submit" value="전송">
    </form>
</body>
</html>
cs

 

요청결과

 

업로드 처리 페이지

/WebContent/fileUpload/multiple_upload_process.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="com.oreilly.servlet.MultipartRequest"%>
<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@ page import="java.util.Enumeration"%>
<html>
<head><title>전송결과</title></head>
<body>
    <%
        request.setCharacterEncoding("UTF-8");
        String savePath = "/fileUpload/upload";
        int uploadFileSizeLimit = 5 * 1024 * 1024;
        String encType = "UTF-8";
        ServletContext context = getServletContext();
        String uploadFilePath = context.getRealPath(savePath);
        try {
            MultipartRequest multi = new MultipartRequest(
                            request, uploadFilePath,
                            uploadFileSizeLimit, encType,
                            new DefaultFileRenamePolicy());
            Enumeration files = multi.getFileNames();
            while (files.hasMoreElements()) {
                String file = (String) files.nextElement();
                String file_name = multi.getFilesystemName(file);
                String ori_file_name = multi.getOriginalFileName(file);
                out.print("<br> 업로드된 파일명 : " + file_name);
                out.print("<br> 원본 파일명 : " + ori_file_name);
                out.print("<hr>");
            }
        } // try 
        catch (Exception e) { System.out.print("예외 발생 : " + e); } // catch
    %>
</body>
</html>
cs

 

동작 확인
1. multiple_upload_form.jsp 를 실행하여 전송할 파일 다중 선택 및 전송
2. multiple_upload_process.jsp 페이지에서 업로드가 처리된 후 결과 내용 출력 확인

반응형

+ Recent posts