JSP 9강 - FileUpload

voilà!·2022년 1월 16일
0

JSP 스프링

목록 보기
9/31

파일 업로드란?

웹 브라우저에서 서버로 파일을 전송하여 서버에 저장하는 것
이미지 파일, binary파일, 문서, 텍스트 파일
폼 태그 내에 사용되어야 함. 오픈 라이브러리(common-fileupload)를 사용
서버로 파일이 업로드 되면? 서버는 요청 파라미터를 분석하여 파일을 찾고
파일 저장 폴더에 저장. 이 처리는 단순한 자바 코드로 작성 불가.

오픈 라이브러리(common-fileupload) jar 추가하기
MVNrepository에서 commons-fileupload 검색 후 Apache Commons FileUpload 클릭
1.4버전 클릭 후 jar 클릭
commons-io 검색 후 2.11.0 버전 클릭 jar 클릭

WEB-INF에 복붙하고
톰캣이 있는 D:\B_Util\5.ApacheTomcat\apache-tomcat-8.5.37\lib 에도 넣기

JSPBOOK properties 에서 java buid path - add External jars - 받은 jar 파일 넣고 apply

fileupload01.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<!-- 
* 파일 업로드란?
 - 웹 브라우저에서 서버로 파일을 전송하여 서버에 저장하는 것
 - 이미지 파일, binary 파일, 문서, 텍스트 파일
 - 폼 태그 내에 사용되어야 함. 오픈 라이브러리(common-fileupload)를 사용.
 - 서버로 파일이 업로드되면? 서버는 요청 파라미터를 분석하여 파일을 찾고
 	파일 저장 폴더에 저장.이 처리는 단순한 자바 코드로 작성 불가.
 -->
<form name="frm" method="post" action="fileupload01_process.jsp" enctype="multipart/form-data">
	<p>파 일 : <input type="file" name="filename" /></p>
	<p><input type="submit" value="파일 올리기" /></p>
</form>
</body>
</html>

fileupload01_process.jsp

<%@ page import="java.io.File"%>
<%@ page import="java.util.Iterator"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="java.util.List"%>
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<%
	//파일이 저장되는 경로
	String path = "C:\\upload";

	DiskFileUpload upload = new DiskFileUpload();
	
	//업로드할 파일의 최대 크기(1M)
	upload.setSizeMax(1000000);
	//메모리상에 저장할 최대 크기
	upload.setSizeThreshold(4096);
	//업로드된 파일을 임시 저장
	upload.setRepositoryPath(path);
	//파싱 : 구문분석 + 의미분석
	//items 안에는 파일객체 + 폼 데이터가 섞여있음
	List items = upload.parseRequest(request);
	
	Iterator params = items.iterator();
	//폼 페이지에서 전송된 요청 파라미터가 없을 때까지 반복
	while(params.hasNext()){
		//전송된 요청 파라미터의 이름을 가져오도록 Iterator 객체 타입의 next() 메소드 사용
		FileItem item = (FileItem)params.next();
		
		if(item.isFormField()){ //요청 파라미터가 일반 데이터(text, checkbox, radio..)
			// ex) ?id=a001
			String name = item.getFieldName(); //id
			String value = item.getString("UTF-8"); //a001
			out.print(name = "=" + value + "<br>");
		}else{//폼 페이지에서 전송된 요청 파라미터가 파일(input type='file')
			//요청 파라미터의 이름
			String fileFieldName = item.getFieldName();
			//저장 파일 이름
			String fileName = item.getName();
			//저장 콘텐츠 유형
			String contentType = item.getContentType();
			
			out.print(fileFieldName + "=" + fileName + "(" + contentType + ")");
			//C:\Users\PC-12\Desktop\500.jpg에서
			//500.jpg가 됨
			fileName.substring(fileName.lastIndexOf("\\")+1);
			long fileSize = item.getSize();
			
			//java.io.File -> 파일객체 생성
			File file = new File(path + "/" + fileName);
			//여기서 실제로 파일 생성(복사완료)
			item.write(file);
			
		}
	}
	
%>
</body>
</html>

0개의 댓글