국비지원 JAVA 풀스택 과정/JAVA

[JAVA] 파일 업로드 구현

ODaram 2022. 12. 9. 15:20

★ 파일 업로드 구현
 1. 환경설정
  a. 파일을 업로드 하고 입력폼을 분석하는 cos.jar 라이브러리를 WEB-INF/lib 폴더에 복사한다.
  b. 프로젝트에서 오른쪽 마우스 버튼을 클릭한 후 Build Path 메뉴의 Configure Build Path 메뉴를 클릭한다.
      Java Buil Path에서 Libraries 탭을 클릭하고 Classpath를 클릭한 후 [Add JARs...] 버튼을 클릭해 cos.jar를 추가한다.
  c. src/main/webapp/exam-fileupload 폴더에 uploadFile 폴더를 생성한다.

 << 환경 설정 완료 >> 
2. form 태그에 enctype 속성을 추가하고 속성 값으로 multipart/form-data를 지정한다.

    form 태그의 type 속성값을 post로 지정한다.

 

 

ViewPage.jsp

★ MultipartRequest 클래스 : 파일 업로드 구현 및 폼 요소 구현에 사용한다.
     1. getFileNames() : type 속성값이 file인 입력폼의 name 속성값들을 얻는다.
     2. getParameterNames() : type 속성값이 file이 아닌 입력 폼의 name 속성값들을 얻는다.

★ Enumeration 인터페이스
     getFileNames() 와 getParameterNames()의 반환형은 Enumeration이다.
     Enumeration 인터페이스를 구현한 객체는 요소를 연속적으로 하나씩 생성하며, 
     nextElement ()로 연속적인 요소를 반환한다.

★ DefaultFileRenamePolicy 클래스
  파일을 업로드 할 때 서버에 파일명이 같은 파일이 있을 경우 덮어쓰기를 방지한다.

<fileSelect.jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	/*
★ 파일 업로드 구현
	1.환경설정
		a. 파일을 업로드하고 입력폼을 분석하는 cos.jar 라이브러리를 WEB-INF/lib 폴더에 복사한다.
		b. 프로젝트에서 오른쪽 마우스 버튼을 클릭한 후 Build Path 메뉴의 Configure Build Path 메뉴를 클릭한다.
			Java Build Path에서 Libraries 탭을 클릭하고 Classpath를 클릭한 후 [Add JARs...] 버튼을 클릭하여
			cos.jar를 추가한다.
		c. src/main/webapp/exam-fileupload 폴더에 uploadFile 폴더를 생성한다.
	2.form 태그에 enctype 속성을 추가하고 속성 값으로 'multipart/form-data'를 지정한다.
	3.form 태그의 type 속성값을 'post'로 지정한다.
	4.input 태그의 type 속성값을 'file'로 지정한다.
	*/
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>파일 업로드 화면</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
	<style>
		h2 {padding:30px 0; text-align:center;}
		ul {width:350px; margin:0 auto;}
		ul li {list-style:none; padding:5px 0;}
	</style>
</head>
<body>
	<h2>파일 업로드</h2>
	<form action ="viewPage.jsp" method="post" enctype="multipart/form-data">
		<ul>
			<li><input type="text" name="name" placeholder="작성자 입력" class="form-control" autofocus required></li>
			<li><input type="text" name="title" class="form-control" placeholder="제목 입력"  required></li>
			<li><input type="file" name="uploadFile1" class="form-control"></li>	<!--  위에서 요구한 type = file 은 무조건 하나 있어야한다.  -->
			<li><input type="file" name="uploadFile2" class="form-control"></li>
			<li><input type="submit" value="SUBMIT" class="btn btn-outline-primary"></li>
		</ul>
	</form>
</body>
</html>
<viewPage.jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	/*
		★ MultipartRequest 클래스 : 파일 업로드 구현 및 폼 요소 구현에 사용한다.
			1. getFileNames() : type 속성값이 file인 입력폼의 name 속성값들을 얻는다.
			2. getParameterNames() : type 속성값이 file이 아닌 입력 폼의 name 속성값들을 얻는다.
		
		★ Enumeration 인터페이스
			getFileNames() 와 getParameterNames()의 반환형은 Enumeration이다.
			Enumeration 인터페이스를 구현한 객체는 요소를 연속적으로 하나씩 생성하며, 
			nextElement ()로 연속적인 요소를 반환한다.
		
		★ DefaultFileRenamePolicy 클래스
		 	파일을 업로드 할 때 서버에 파일명이 같은 파일이 있을 경우 덮어쓰기를 방지한다.
	*/
%>

<%@ page import="com.oreilly.servlet.MultipartRequest" %>
<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy" %>
<%@ page import="java.util.Enumeration" %>
<%@ page import="java.io.File" %>
<%@ page import="java.io.IOException" %>

<%
//업로드 파일을 저장할 폴더(uploadFile)의 경로를 저장하는 saveFolder 변수 선언
	String saveFolder = "D:/{workspace-java}/ReadyProject/src/main/webapp/exam-fileupload/uploadFile";
	String encType = "utf-8"; // 파일명이 한글일 경우 인코딩 설정을 저장할 encType 변수 선언
	int maxSize = 5 * 1024 * 1024; // 5MB 업로드 최대 크기를 저장할 maxSize 변수 선언
	
	String name = null, fileName = null, value = null, filename = null, original = null, type = null;
	
	try {
		MultipartRequest multi = new MultipartRequest(request, saveFolder, maxSize, encType, new DefaultFileRenamePolicy());	//첫번째 request 는 무조건 들어간다.
		// DefaultFileRenamePolicy : 파일명 뒤에 (1)과 같이 구별자를 붙이므로써 중복 방지한다.
		
		Enumeration params = multi.getParameterNames();		
		Enumeration files = multi.getFileNames(); 
	
		/*
		while (params.hasMoreElements( )) {
			// params.hasMoreElements( )는 params에 요소가 있으면 true를 반환한다.
			name = (String) params.nextElement( );
			// params에서 파라미터의 이름(input 요소의 이름)을 얻어 String형으로 캐스팅한다. getParameter(str)의 매개변수로 문자열형을 지정해야한다.
			value = multi.getParameter(name);
			// 파라미터 이름(input 요소의 이름)으로 input 요소에 입력된 값을 얻는다.
			out.println(name + " = " + value + "<br>");
			// JSP의 out 내장 객체로 브라우저에 출력한다.
		}
		*/	
	
		/*
		while(files.hasMoreElements()) { //files에 요소(name 속성)가 있으면
			fileName = (String) files.nextElement();
			filename = multi.getFilesystemName(fileName);
			original = multi.getOriginalFileName(fileName);
			type = multi.getContentType(fileName);
			File file = multi.getFile(fileName);
			
			out.println("파라미터의 name 속성값" + fileName + "<br>");
			out.println("서버에 저장된 파일 이름" + filename + "<br>");
			out.println("원본 파일 이름" + original + "<br>");
			out.println("파일 타입" + type + "<br>");
			if(file != null) {
				out.println("파일 크기" + file.length() + "바이트");
			}
		}
		*/
%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>파일 업로드 처리와 정보 출력</title>
</head>
<body>
<%

	while(params.hasMoreElements()) { 	//params에 요소(name 속성)가 있으면
		name = (String) params.nextElement();
		value = multi.getParameter(name);
%>
	<ul>
		<li>name 속성 값: <%=name %></li>
		<li>사용자 입력 값: <%=value %></li>
	</ul>
	
	<%
		}

		while(files.hasMoreElements()) { //files에 요소(name 속성)가 있으면
			fileName = (String) files.nextElement();
			filename = multi.getFilesystemName(fileName);
			original = multi.getOriginalFileName(fileName);
			type = multi.getContentType(fileName);
			File file = multi.getFile(fileName);
			long size = file.length();
%>
	
	<ul>
		<li>서버에 저장된 파일 이름 : <%=filename %></li>
		<li>원본 파일 이름 : <%=original %></li>
		<li>파일 타입 : <%=type %></li>
		<li>파일 크기 : <%=size %> 바이트</li>
	</ul>
<% 
	}
}
catch(IOException ioe) {System.out.println(ioe);}
catch(Exception e) {System.out.println(e);}
%>
</body>
</html>

    

'국비지원 JAVA 풀스택 과정 > JAVA' 카테고리의 다른 글

[JSP] 회원관리 프로그램2  (0) 2022.12.13
[JSP] 회원관리 프로그램  (0) 2022.12.12
[JAVA] 자동 줄바꿈 처리  (0) 2022.12.09
[JAVA] JSP 수업 정리  (0) 2022.12.09
[JAVA] 로그인 session 예제  (0) 2022.12.08