파일 업로드 하기3 - Function

Published on: 2009. 3. 31. 17:38 by louis.dev

<!-- FileUpload Function -->
참조:: http://javastore.tistory.com/entry/파일-업로드-하기


void fileUpload (HttpServletRequest request, String realPath, Map<String, String> parameters, 
                      Map<String, UploadFile> uploadFiles) throws FileUploadException, UnsupportedEncodingException {
 boolean isMultipart = ServletFileUpload.isMultipartContent(request);

 if( isMultipart ) {
  File temporaryDir = new File("c:\\tmp\\");
  
  DiskFileItemFactory factory = new DiskFileItemFactory();
  factory.setSizeThreshold(0);
  factory.setRepository(temporaryDir);
 
  ServletFileUpload upload = new ServletFileUpload(factory);
  upload.setSizeMax(10 * 1024 * 1024);
  List<FileItem> items = upload.parseRequest(request);
  
  Iterator iter = items.iterator();
  while (iter.hasNext()) {
   FileItem fileItem = (FileItem) iter.next();
 
   if (fileItem.isFormField()) {
    parameters.put(fileItem.getFieldName(), fileItem.getString("euc-kr"));
    //out.println("폼 파라미터 : " + fileItem.getFieldName() + "=" + fileItem.getString("euc-kr") + "<br/>");
   } else {
   if( fileItem.getSize() > 0 ) {
    UploadFile uf = new UploadFile();
 
    String fieldName = fileItem.getFieldName();
 
    int idx = fileItem.getName().lastIndexOf("\\");
    if( idx == -1 ) {
     idx = fileItem.getName().lastIndexOf("/");
    }
    String fileName = fileItem.getName().substring(idx + 1);
 
    
    String contentType = fileItem.getContentType();
    boolean isInMemory = fileItem.isInMemory();
    long sizeInBytes = fileItem.getSize();
 
    uf.setFileName(fileName);
    uf.setTempName(fileName);
    uf.setContentType(contentType);
    uf.setFileSize(sizeInBytes);
    
    uploadFiles.put(fileItem.getFieldName(), uf);
    
    
    try {
     File uploadedFile = new File(realPath, fileName);
     fileItem.write(uploadedFile);
     //fileItem.delete();
    } catch(Exception ex) {}
   }
   }
  }
 } else {
  out.println("인코딩 타입이 multipart/form-data 가 아님.");
 }
}

=========================================================================================================
<!-- 실제 사용할때 -->

String realPath = config.getServletContext().getRealPath("/upload/");
Map<String, String> parameters = new HashMap<String, String>();
Map<String, UploadFile> uploadFiles = new HashMap<String, UploadFile>();

 fileUpload(request, realPath, parameters, uploadFiles);
 

 UploadFile uf1=uploadFiles.get("file1");                                    //write_form.jsp 의 input name='file1'
 UploadFile uf2=uploadFiles.get("file2");
 UploadFile uf3=uploadFiles.get("file3");

 String title = parameters.get( "title" );                                        //post형식으로 보내면 getParameter로 받는것이 아니라
 String contents = parameters.get( "contents" );                         //Map<String, String> parameters = new HashMap<String, String>();
 String userId=(String)session.getAttribute("userId");                  //parameters.get으로 한다.

======================================================================================================
write_form.jsp

<form name='writeFrm' action='write.jsp' method='post'  enctype='multipart/form-data'>
       <table width="690" border="1" cellpadding="10" cellspacing="0" style="border:solid 1px #d6d7d6;">
           
            <tr>
              <td align="left">제목</td>
              <td align="left"><input name="title" type="text" value="" size="40" /></td>
            </tr>
            <tr>
             <td>내용</td>
             <td><textarea name='contents' cols='70' rows='10'></textarea></td>
            </tr>
            <tr>
                <td colspan="2">
                 파일1: <input type="file" name="file1" size='50'/><br>
                 파일2: <input type="file" name="file2" size='50'/><br>
                  파일3: <input type="file" name="file3" size='50'/><br>
                 </td>
            </tr>
            <tr>
               <td colspan="2" align="right">
                 <img src="/images/button_save.gif" width="67" height="30" style="cursor:hand;" onclick="javascript:checkUserRegist();" />
            </tr>
           
         </table>
      </form>

Name
Password
Homepage
Secret