본문 바로가기

프로그래밍/JSP

파일 업로드


1. FileUpload API 다운로드


2개의 라이브러리 다운로드

1) commons-fileupload-1.3.3.jar

http://commons.apache.org/proper/commons-fileupload/download_fileupload.cgi

2) commons-io-2.5.jar

http://commons.apache.org/proper/commons-io/download_io.cgi

2. FileUploadForm.jsp - Form 태그를 이용해서 파일 전송

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>파일 업로드</title>
</head>
<body>
 
<h1>파일 업로드</h1>
<!-- 필수 입력 - method ="post" enctype="multipart/form-data" -->
<form action="upload.jsp" method="post" enctype="multipart/form-data">
 
    <input type = "text" name ="name"><br/>
    <input type ="file" name="photo"><br/>
    <input type = "submit">
</form>
 
</body>
</html>
cs


3. upload.jsp - Form 처리 페이지

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
    String imgName ="";
    //서비스클래스 (JAVA) 파일로 처리하는것이 좋다.
 
    //1. multiport/form-data 여부 확인
    
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    
if (isMultipart) {
    // 2. 메모리나 파일로 업로드 파일 보관하는 FileItem의 Factory 설정
    DiskFileItemFactory factory = new DiskFileItemFactory();
    
    // 3. 업로드 요청을 처리하는 ServletFileUpload 생성
    ServletFileUpload upload = new ServletFileUpload(factory);
    
    // 4. 업로드 요청 파싱해서 FileItem 목록 구함
    
    List<FileItem> items = upload.parseRequest(request);
    
    Iterator<FileItem> iter = items.iterator();
    
    while(iter.hasNext()){
        FileItem item = iter.next();
        
        // 파일인지 여부 확인 : isFormFile() -> type=file 이외의 폼 데이터 인지 확인
            if (item.isFormField()) { // 텍스트 입력인 경우
                String name = item.getFieldName(); //태그 name
                String value = item.getString("utf-8"); 
                System.out.println("일반 폼 필드 :" + name+ "-" + value);
            }else{
                String name = item.getFieldName();
                String fileName = item.getName(); //파일이름
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize(); //파일 사이즈
                
                System.out.println("파일 이름 :" + fileName);
                
                // 저장하고자 하는 파일의 이름
                imgName = "cool_" + fileName;
                
                //웹서비스에서 사용되는 저장 경로
                String uploadUri = "/file/photo";
                
                // 물리적인 경로
                String dir = request.getSession().getServletContext().getRealPath(uploadUri);
                System.out.println(uploadUri+"의 물리적 경로 : "+ dir);
                
                // 데이터 저장 File(위치, 파일명)
                // 만들어놓은 웹컨텐트 /file/photo/___ <이곳에 저장하기 위해 경로를 지정한것(물리적으로)
                item.write(new File(dir, imgName));
                
            }
        }
 
    }
%>
 
 
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    저장한 이미지를 출력 <br>
    <img alt="사진" src="file/photo/<%=imgName%>"/>
</body>
</html>
cs
cd

4. 실행화면

 FileUploadForm.jsp

upload.jsp

upload.jsp - 콘솔결과창



예제를 이용해서 활용

1)회원가입시 회원사진업로드, 마이페이지에서 회원사진 확인가능

2)회원배경사진 지정시 로그인 했을 시 회원아이디 옆에 배경사진 --> 세션에 이미지를 담아서


'프로그래밍 > JSP' 카테고리의 다른 글

JDBC - JDBC 프로그래밍 예제(1)  (0) 2018.07.21
필터 - 캐릭터 인코딩  (0) 2018.07.21
MVC 패턴 구현  (0) 2018.07.19
필터 - 로그인 검사 필터  (0) 2018.07.19
JSP 환경구축2 (이클립스 설정)  (0) 2018.06.09