DS's『 행복합시다 』

Carpe Programming/jsp & spring & jstl

[jsp] commons-fileupload 를 이용한 간단한 파일 업로드

nolite 2012. 7. 11. 13:58
반응형

[test.html]

 

<html>
<head>
    <title>Upload Test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="/common/js/jquery.js"></script>
<script type="text/javascript" src="/common/js/common.js"></script>
<script type="text/javascript">
        function goUpload() {
            $("#uploadFrm").submit();
        }
</script>   
</head>
<body>
    <form name="uploadFrm" id="uploadFrm" method="post" action="test3_proc.jsp" enctype="multipart/form-data">
        <table>
        <tr>
            <td><input type="file" name="uploadFile" id="uploadFile"/></td>
        </tr>
        </table>
        <input type="button" value="UPLOAD" onclick="javascript:goUpload();"/>
    </form>
</body>
</html>

 

 

[test3_proc.jsp]

 

<%@ page language = "java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import   = "java.io.*"%>
<%@ page import   = "java.util.List"%>
<%@ page import   = "com.intra.util.*"%>
<%@ page import   = "org.apache.log4j.Logger"%>
<%@ page import   = "org.apache.commons.fileupload.*"%>


<%
 Logger log = Logger.getLogger(request.getRequestURI());

 //upload path
 //String path = "C:/project/mars/mars/WebContent/upload/biz";
    String path = FileConfig.getInstance().getProperty("WEB_ROOT_PATH") + FileConfig.getInstance().getProperty("UPLOAD_BIZ");
           path = path.replaceAll("\\\\","/");

    //폴더가 존재하지 않을 경우 생성
    File isDir = new File(path);
    if(!isDir.isDirectory()){
        isDir.mkdirs();
    }

    
 DiskFileUpload upload = new DiskFileUpload();
 
 upload.setSizeMax(10 * 1024 * 1024);       //파일  업로드  최대  size : 10메가
 upload.setSizeThreshold(4096);             //메모리에  저장할  최대  size                
 upload.setRepositoryPath(path);            //파일  임시  저장소
 List items = upload.parseRequest(request);
 
 FileItem item1            = (FileItem) items.get(0);
 String   prefix            = "Purchase_";                    // upload 구분
 long     fileSize         = item1.getSize();                 // 파일 크기 얻기
 String   realFileName = item1.getName();               // 원본 파일명 얻기(DB 저장용)
            realFileName = realFileName.substring(realFileName.lastIndexOf("\\") + 1);
         
 // upload 파일 이름 지정(prefix + 시각)
 String   fileName   = prefix + DateUtil.getCurrentTimeString() + realFileName.substring(realFileName.lastIndexOf("."));
 File      file           = new File(path + "/" + fileName); // 경로 + 파일명 지정
 
 log.debug("fileSize         : " + item1.getSize());
 log.debug("file               : " + file);
 log.debug("realFileName : " + realFileName);
 log.debug("fileName       : " + fileName);
 
 item1.write(file);  // 파일 저장
 
 log.debug(realFileName + " 저장 완료!!!");
%>

 

 

[참고] - http://blog.naver.com/sungback?Redirect=Log&logNo=90027038968

 

 

 

 

 

728x90
반응형