티스토리 뷰

출처를 밝힙니다.
출처 : http://blog.naver.com/adflizard?Redirect=Log&logNo=10143290298

 

//참고하자!

 

1. jsp 설정 부분.

<form:form commandName="fboNoticeVO" name="noticeForm" id="noticeForm" method="post" action="${basePath}/noticeBoard/notice/boardWriteProc.do" enctype="multipart/form-data" onsubmit="return fn_egov_save();">

 

<input type="file" name="file1" size="70" />

 

2. controller 설정 부분.

 @RequestMapping("/noticeBoard/notice/boardWriteProc.do")
    public String insertNoticeProc(
      @ModelAttribute("defaultVO")DefaultVO defaultVO,Map commandMap
      ,FboNoticeVO fboNoticeVO, BindingResult bindingResult, Model model
      ,HttpServletRequest request, HttpServletResponse response, SessionStatus status )throws Exception{
        HttpSession session = request.getSession();
        request.getSession().setAttribute("FboNoticeVO", fboNoticeVO);
     
      beanValidator.validate(fboNoticeVO, bindingResult);
      System.out.println("/**공지사항 등록*/==============="+commandMap);
            if (bindingResult.hasErrors()) {
                model.addAttribute("fboNoticeVO", fboNoticeVO);
                return "/fbo/noticeBoard/notice/write";
            }
                      
            //사용자 인증
            boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
      if (isAuthenticated) {
        UserDetailsVO userDetailsVO = 
        (UserDetailsVO)EgovUserDetailsHelper.getAuthenticatedUser();
        String registId = userDetailsVO.getUserId();
        String registName=userDetailsVO.getUserName();
        fboNoticeVO.setRegistId(registId);
        fboNoticeVO.setRegistName(registName);
      }            
            
            int noticeSeq=idGnrServiceNotice.getNextIntegerId();
            
            
            //파일업로드
         MultipartHttpServletRequest mptRequest = (MultipartHttpServletRequest)request;
         Iterator fileIter = mptRequest.getFileNames();
         
         HashMap fileMap = new HashMap();//db에 넣을해쉬맵
         
         ArrayList result = new ArrayList();
         while (fileIter.hasNext()) {
             MultipartFile mFile = mptRequest.getFile((String)fileIter.next());

             if (mFile.getSize() > 0) {
          HashMap map = EgovFileMngUtil.uploadFile(mFile);
          
             int fileSeq = idGnrServiceFile.getNextIntegerId();
             int fileBoardSeq = noticeSeq;          
             String boardType = (String)commandMap.get("boardType");
             String originalName = (String)map.get(Globals.ORIGIN_FILE_NM);
             String fileName = (String)map.get(Globals.UPLOAD_FILE_NM);
             String fileSize = (String)map.get(Globals.FILE_SIZE);
             String filePath = (String)map.get(Globals.FILE_PATH); 
             String fileExt = (String)map.get(Globals.FILE_EXT);
             
             fileMap.put("fileSeq", fileSeq);
             fileMap.put("fileBoardSeq", fileBoardSeq);
             fileMap.put("boardType", boardType);
             fileMap.put("originalName", originalName);
             fileMap.put("fileName", fileName);
             fileMap.put("fileSize", fileSize);
             fileMap.put("filePath", filePath);
             fileMap.put("fileExt", fileExt);
             
          fboBoardService.fileUploadServiceProc(fileMap); 
             }
         }
            
            fboNoticeVO.setNoticeSeq(noticeSeq);
            fboBoardService.insertNoticeProc(fboNoticeVO);
            status.setComplete();
            session.removeAttribute("FboNoticeVO");
            return "redirect:/noticeBoard/notice/noticeList.do";
    }

 

    /**
     * 공지사항을 삭제한다.
     * @param sampleVO
     *        - 수정할 정보가 담긴 VO
     * @param defaultVO
     *        - 목록 조회조건 정보가 담긴 VO
     * @param status
     * @return "redirect:/sample/egovSampleList.do"
     * @exception Exception
     */
    @RequestMapping("/noticeBoard/notice/deleteNotice.do")
 public String deleteNoticeProc(Map commandMap, Model model){
     System.out.println("/**공지사항을 삭제한다.*/"+commandMap);
     String noticeSeq=(String)commandMap.get("noticeSeq");
     commandMap.put("seq", commandMap.get("noticeSeq"));
     fboBoardService.deleteNotice(noticeSeq);
     Map fileList =fboBoardService.loadDownloadFile(commandMap);
     if(fileList != null){
         String stordFilePath = EgovProperties.getProperty("Globals.fileStorePath");
         fboBoardService.deleteFileAll(commandMap); //전체파일삭제

         Map fileInfo;
         List fileListReult=(List)fileList.get("result");
         for(int i=0; i<fileListReult.size();i++){
          fileInfo=(Map)fileListReult.get(i);
          String filePath = stordFilePath + "/" +fileInfo.get("fileName");;
          fboBoardService.deleteFile(filePath);//지정된 경로에 저장된파일 삭제
         }
     }

     model.addAttribute("commandMap", commandMap);
     return "redirect:/noticeBoard/notice/noticeList.do";
 }
   

 

3. 인터페이스 부분

 

/** 파일 업로드*/
 public void fileUploadServiceProc(Map commandMap)throws Exception;
 
 /** 다운로드할파일의정보가져오기*/
 public Map loadDownloadFile(Map commandMap);
 
 
  /**
  * 파일삭제 */
 public void deleteFileAll(Map commandMap);
 
  /**
  * 첨부파일을 삭제한다. */
 public void deleteSelectedFile(Map commandMap);
 
 /** 파일삭제*/
 public String deleteFile(String fileDeletePath);
 
 /** 파일삭제*/
 public String deletePath(String filePath);

 

4. 파일관련 구현부분

    /**
     * 첨부로 등록된 파일을 서버에 업로드한다.
     * 
     * @param file
     * @return
     * @throws Exception
     */
    public static HashMap<String, String> uploadFile(MultipartFile file) throws Exception {

 HashMap<String, String> map = new HashMap<String, String>();
 //Write File 이후 Move File????
 String newName = "";
 String stordFilePath = EgovProperties.getProperty("Globals.fileStorePath");
 String orginFileName = file.getOriginalFilename();

 int index = orginFileName.lastIndexOf(".");
 //String fileName = orginFileName.substring(0, _index);
 String fileExt = orginFileName.substring(index + 1);
 long size = file.getSize();

 //newName 은 Naming Convention에 의해서 생성
 newName = EgovStringUtil.getTimeStamp() + "." + fileExt;
 writeFile(file, newName, stordFilePath);
 //storedFilePath는 지정  
 map.put(Globals.ORIGIN_FILE_NM, orginFileName);
 map.put(Globals.UPLOAD_FILE_NM, newName);
 map.put(Globals.FILE_EXT, fileExt);
 map.put(Globals.FILE_PATH, stordFilePath);
 map.put(Globals.FILE_SIZE, String.valueOf(size));

 return map;
    }
    
    
    /**
     * 파일을 실제 물리적인 경로에 생성한다.
     * 
     * @param file
     * @param newName
     * @param stordFilePath
     * @throws Exception
     */
    protected static void writeFile(MultipartFile file, String newName, String stordFilePath) throws Exception {
 InputStream stream = null;
 OutputStream bos = null;
 
 try {
     stream = file.getInputStream();
     File cFile = new File(stordFilePath);

     if (!cFile.isDirectory())
  cFile.mkdir();

     bos = new FileOutputStream(stordFilePath + File.separator + newName);

     int bytesRead = 0;
     byte[] buffer = new byte[BUFF_SIZE];

     while ((bytesRead = stream.read(buffer, 0, BUFF_SIZE)) != -1) {
  bos.write(buffer, 0, bytesRead);
     }
 } catch (FileNotFoundException fnfe) {
     fnfe.printStackTrace();
 } catch (IOException ioe) {
     ioe.printStackTrace();
 } catch (Exception e) {
     e.printStackTrace();
 } finally {
     if (bos != null) {
  try {
      bos.close();
  } catch (Exception ignore) {
      Logger.getLogger(EgovFileMngUtil.class).debug("IGNORED: " + ignore.getMessage());
  }
     }
     if (stream != null) {
  try {
      stream.close();
  } catch (Exception ignore) {
      Logger.getLogger(EgovFileMngUtil.class).debug("IGNORED: " + ignore.getMessage());
  }
     }
 }
    }
 
    
    /**
  * 파일업로드 서비스
  * @param searchVO - 조회할 정보가 담긴 VO
  * @return 글 목록
  * @exception Exception
  */
    public void fileUploadServiceProc(Map map) throws Exception{
      System.out.println("fileUploadServiceProc==============="+map);
     fboBoardDAO.fileUploadServiceProcDao(map);
    }
 
  /**
  * 다운로드할파일의정보가져오기 */
 public Map loadDownloadFile(Map commandMap) {
  Map fileMap=new HashMap();
  List result= fboBoardDAO.loadDownloadFileDao(commandMap);
  int fileCnt=fboBoardDAO.loadDownloadFileCntDao(commandMap);
  fileMap.put("result", result);
  fileMap.put("fileCnt", fileCnt);
  System.out.println("loadDownloadFile서비스임플======================="+result);
  return fileMap;
 }
 
  /**
  * 파일삭제 */
 public void deleteFileAll(Map commandMap) {
  fboBoardDAO.deleteFileAllDao(commandMap);
 }
 
  /**
  * 첨부파일을 삭제한다. */
 public void deleteSelectedFile(Map commandMap) {
  fboBoardDAO.deleteSelectedFileDao(commandMap);
 }
 
 /**
     * <pre>
     * Comment : 파일을 삭제한다. 
     * </pre>
     * @param fileDeletePath 삭제하고자 하는파일의 절대경로
     * @return 성공하면  삭제된 파일의 절대경로, 아니면블랭크
     */

    public  String deleteFile(String fileDeletePath){
        
        // 인자값 유효하지 않은 경우 블랭크 리턴
        if (fileDeletePath==null || fileDeletePath.equals("")){
            return "";
        }
        String result="";
        File file = new File(fileDeletePath);
        if(file.isFile()){
            result = deletePath(fileDeletePath);
        }else{
            result = "";
        }
        
        return result;
    }

    
    
    public  String deletePath(String filePath){
        File file = new File(filePath);
        String result = "";
        try{
            /*
            if(!file.exists()){
             //log.debug("File Exist..");
            }else{
                result = file.getAbsolutePath();
                if(!file.delete()){
                    result="";
                }
            } 
            */ 
           if(file.exists()){
                result = file.getAbsolutePath();
                if(!file.delete()){
                    result="";
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

 

4. DAO구현 부분

    /**
  * 파일업로드하기
  * @param defaultVO 
  * @return 글 목록
  * @exception Exception
  */
    public void fileUploadServiceProcDao(Map commandMap){
     System.out.println("fileUploadServiceProcDao==============="+commandMap);
     insert("fileUploadServiceProc", commandMap);
    }
    
    /**
  * 파일다운로드
  * @param defaultVO 
  * @return 글 목록
  * @exception Exception
  */
    public List loadDownloadFileDao(Map commandMap){
     return list("loadDownloadFile", commandMap);
    }
    
    /**
  * 파일갯수
  * @param defaultVO 
  * @return 글 목록
  * @exception Exception
  */
    public int loadDownloadFileCntDao(Map commandMap) {
     Integer iCnt = (Integer)getSqlMapClientTemplate().queryForObject("loadDownloadFileCnt", commandMap);
     int cnt = iCnt == null ? 0 : iCnt.intValue();
     return cnt;
    }
    
     
    /**
  * 파일삭제
  * @param defaultVO 
  * @return 글 목록
  * @exception Exception
  */
    public void deleteFileAllDao(Map commandMap){
     delete("deleteFileAll", commandMap);
    }
    
    /**
  * 첨부파일을 삭제한다.
  * @param defaultVO 
  * @return 글 목록
  * @exception Exception
  */
    public void deleteSelectedFileDao(Map commandMap){
     delete("deleteSelectedFile", commandMap);
    }

 

5. 파일관련 sql부분

 

 <!-- 다운로드할파일의 정보를 가져온다 -->
 <select id="loadDownloadFile" resultClass="egovMap">
  SELECT * FROM FBO_FILE_T 
  WHERE FILE_BOARD_SEQ=#seq#
  AND BOARD_TYPE = #boardType#
  ORDER BY FILE_SEQ
 </select>
 
 <!-- 다운로드할파일의 갯수 -->
 <select id="loadDownloadFileCnt" resultClass="java.lang.Integer">
  SELECT COUNT(*) FROM FBO_FILE_T 
  WHERE FILE_BOARD_SEQ=#seq#
  AND BOARD_TYPE = #boardType#
  ORDER BY FILE_SEQ
 </select>

 

<!--글삭제시파일삭제 -->
 <delete id="deleteFileAll">
  DELETE FROM FBO_FILE_T 
  WHERE FILE_BOARD_SEQ=#fileSeq#
  AND BOARD_TYPE = #boardType#
 </delete>
 
 <!--첨부파일삭제 -->
 <delete id="deleteSelectedFile">
  DELETE FROM FBO_FILE_T 
  WHERE FILE_SEQ = #fileSeq#
  AND BOARD_TYPE = #boardType#
 </delete>

 

 

 

[출처] 파일 업로드|작성자 짠지


공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함