Language/Java / JSP

[JSP] cos.jar를 이용한 파일 업로드 구현하기

과일가게 개발자 2014. 8. 20. 12:30
반응형

JSP에서 게시판등을 만들다보면 필수로 필요한 기능이 파일 업로드 기능이다.
파일 업로드 기능은 java에서 기본으로 지원해주지 않지만, 오픈 라이브러리를 이용하면 쉽게 구현이 가능하다.

파일 업로드 라이브러리에는 대표적으로 commons-fileupload.jar 와 cos.jar가 있다.
오늘은 cos.jar 라이브러리를 이용해서 파일 업로드 기능을 구현해 보자.



cos.jar




1. cos.jar 파일 추가 : {documentRoot}/WEB-INF/lib/



2. 파일 전송 form 화면 작성(uploadForm.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<title>파일 업로드 폼</title>
</head>

<body>

<form name="fileForm" id="fileForm" method="POST" action="fileUpload.jsp" enctype="multipart/form-data">
	<input type="text" name="title" id="title">
	<input type="file" name="uploadFile" id="uploadFile"> 
	<input type="submit" value="전송">
</form>
</body>
</html>



파일 업로드를 하기 위해선 form 태그에 enctype="multipart/form-data" 부분이 명시되어야 한다.
또한 파일을 선택할수 있는 input 박스는 type을 file로 지정하면 된다. input type="file"



3. 파일 업로드 구현부 작성(uploadOK.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8" %>

<%@page import="com.oreilly.servlet.MultipartRequest" %>
<%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy" %>
<%@page import="java.io.*" %>
<%@page import="java.util.Date" %>
<%@page import="java.text.SimpleDateFormat" %>

<%
	request.setCharacterEncoding("UTF-8");

	// 10Mbyte 제한
	int maxSize  = 1024*1024*10;		

	// 웹서버 컨테이너 경로
	String root = request.getSession().getServletContext().getRealPath("/");

	// 파일 저장 경로(ex : /home/tour/web/ROOT/upload)
	String savePath = root + "upload";

	// 업로드 파일명
	String uploadFile = "";

	// 실제 저장할 파일명
	String newFileName = "";



	int read = 0;
	byte[] buf = new byte[1024];
	FileInputStream fin = null;
	FileOutputStream fout = null;
	long currentTime = System.currentTimeMillis();  
	SimpleDateFormat simDf = new SimpleDateFormat("yyyyMMddHHmmss");  

	try{

		MultipartRequest multi = new MultipartRequest(request, savePath, maxSize, "UTF-8", new DefaultFileRenamePolicy());
		
		// 전송받은 parameter의 한글깨짐 방지
		String title = multi.getParameter("title");
		title = new String(title.getBytes("8859_1"), "UTF-8");

		// 파일업로드
		uploadFile = multi.getFilesystemName("uploadFile");

		// 실제 저장할 파일명(ex : 20140819151221.zip)
		newFileName = simDf.format(new Date(currentTime)) +"."+ uploadFile.substring(uploadFile.lastIndexOf(".")+1);

		
		// 업로드된 파일 객체 생성
		File oldFile = new File(savePath + uploadFile);

		
		// 실제 저장될 파일 객체 생성
		File newFile = new File(savePath + newFileName);
		

		// 파일명 rename
		if(!oldFile.renameTo(newFile)){

			// rename이 되지 않을경우 강제로 파일을 복사하고 기존파일은 삭제

			buf = new byte[1024];
			fin = new FileInputStream(oldFile);
			fout = new FileOutputStream(newFile);
			read = 0;
			while((read=fin.read(buf,0,buf.length))!=-1){
				fout.write(buf, 0, read);
			}
			
			fin.close();
			fout.close();
			oldFile.delete();
		}   

	}catch(Exception e){
		e.printStackTrace();
	}

%>




위와같이 MultipartRequest 부분에서 파일 업로드 부분을 처리한다.


나같은경우 파일을 저장할때 "20140819151221.zip" 같이 파일명을 rename하여 주로 사용한다.
이유는 예전에 EUC-KR 서버에 한글로 된 파일을 저장했다가 파일명이 깨지는 경우가 발생하여 복구가 어려웠던 기억이 있다.
요즘은 왠만한 서버들이 UTF-8로 맞춰져 있어서 큰 상관은 없지만 한번 생긴 습관이 무섭다.

또 서버 로케일이 다른 환경으로 이관할때 문제도 적기도 하다.

그런이유로 파일 업로드시 원래 파일명과 변경된 파일명을 DB에 저장하고 파일 다운로드 구현시 원본 파일명으로 내보낸다.