8_Spring(파일업로드1)

study/Spring · 2020. 3. 9. 09:03

jsp에서는 cos.jar를 사용했음 spring에서는 새로운 라이브러리를 사용

maven에서 commons-filiupload 검색

Apache Commons FileUpload
1.3.3버전

단독으로 사용안되서 같이 사용되는 
Apache Commons IO (입출력)
2.6 버전

pom.xml에 추가

  <!-- 파일 업로드 관련 라이브러리 --> 
  <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
  <dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.3</version>
  </dependency>

  <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
  <dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.6</version>
  </dependency>

root-context.xml에 파일업로드 관련 bean 등록

MultipartResover

<!-- 파일업로드 관련 bean 등록 -->
<!-- MultipartResover -->
<bean id="multipartResolver"
	class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="20000000"/> <
    <property name="maxInmemorySize" value="10000000"/>
</bean>
<!-- 20000000 : 약 20메가
	maxUploadSize : 
    	한 요청당 업로드가 허용되는 최대 용량(단위:byte)
        기본값은 -1 (-1은 제한이 없다라는 뜻)
    maxInMemorySize :
    	디스크(하드) 저장하지 않고 메모리에 유지하도록
        허용하는 바이트 단위 최대 용량 설정
        
        사이즈가 지정된 크기보다 큰 경우
        초과되는 데이터는 바로 파일로 저장됨
        기본값은 10240바이트 (10kb)
	-->

DB에 새로운 이름으로 저장하기 위한 FileRename Class

package com.kh.spring.common;

import java.text.SimpleDateFormat;

public class FileRename {
	public static String rename(String originFileName) {
    
    	SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
        String date = sdf.format(new java.util.Date(System.currentTimeMillis()));
        
        StringBuffer sb = new StringBuffer();
        for(int i=0; i<6; i++) {
        	sb.append((int)(Math.random()*10));
        }
        
        String ext = originFileName.substring(originFileName.lastIndexOf("."));
        
        return date + "_" + sb.toString() + ext;
    }
}

 

Attachment (파일 정보를 DB에 담기위한 vo)

package com.kh.spring.board.model.vo;

import java.sql.Date;

public class Attachment {
	private int fileNo;
	private int boardId;
	private String fileOriginName;
	private String fileChangeName;
	private String filePath;
	private Date fileUploadDate;
	private int fileLevel;
	private int fileDownloadCount;
	private String fileStatus;
	
	public Attachment() {
		
	}

	public Attachment(int fileNo, int boardId, String fileChangeName) {
		super();
		this.fileNo = fileNo;
		this.boardId = boardId;
		this.fileChangeName = fileChangeName;
	}
	
	

	public Attachment(String fileOriginName, String fileChangeName, String filePath) {
		super();
		this.fileOriginName = fileOriginName;
		this.fileChangeName = fileChangeName;
		this.filePath = filePath;
	}

	public Attachment(int fileNo, int boardId, String fileOriginName, String fileChangeName, String filePath,
			Date fileUploadDate, int fileLevel, int fileDownloadCount) {
		super();
		this.fileNo = fileNo;
		this.boardId = boardId;
		this.fileOriginName = fileOriginName;
		this.fileChangeName = fileChangeName;
		this.filePath = filePath;
		this.fileUploadDate = fileUploadDate;
		this.fileLevel = fileLevel;
		this.fileDownloadCount = fileDownloadCount;
	}

	public Attachment(int fileNo, int boardId, String fileOriginName, String fileChangeName, String filePath,
			Date fileUploadDate, int fileLevel, int fileDownloadCount, String fileStatus) {
		super();
		this.fileNo = fileNo;
		this.boardId = boardId;
		this.fileOriginName = fileOriginName;
		this.fileChangeName = fileChangeName;
		this.filePath = filePath;
		this.fileUploadDate = fileUploadDate;
		this.fileLevel = fileLevel;
		this.fileDownloadCount = fileDownloadCount;
		this.fileStatus = fileStatus;
	}


	public int getFileNo() {
		return fileNo;
	}

	public void setFileNo(int fileNo) {
		this.fileNo = fileNo;
	}

	public int getBoardId() {
		return boardId;
	}

	public void setBoardId(int boardId) {
		this.boardId = boardId;
	}

	public String getFileOriginName() {
		return fileOriginName;
	}

	public void setFileOriginName(String fileOriginName) {
		this.fileOriginName = fileOriginName;
	}

	public String getFileChangeName() {
		return fileChangeName;
	}

	public void setFileChangeName(String fileChangeName) {
		this.fileChangeName = fileChangeName;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public Date getFileUploadDate() {
		return fileUploadDate;
	}

	public void setFileUploadDate(Date fileUploadDate) {
		this.fileUploadDate = fileUploadDate;
	}

	public int getFileLevel() {
		return fileLevel;
	}

	public void setFileLevel(int fileLevel) {
		this.fileLevel = fileLevel;
	}

	public int getFileDownloadCount() {
		return fileDownloadCount;
	}

	public void setFileDownloadCount(int fileDownloadCount) {
		this.fileDownloadCount = fileDownloadCount;
	}

	public String getFileStatus() {
		return fileStatus;
	}

	public void setFileStatus(String fileStatus) {
		this.fileStatus = fileStatus;
	}

	@Override
	public String toString() {
		return "Attachment [fileNo=" + fileNo + ", boardId=" + boardId + ", fileOriginName=" + fileOriginName
				+ ", fileChangeName=" + fileChangeName + ", filePath=" + filePath + ", fileUploadDate=" + fileUploadDate
				+ ", fileLevel=" + fileLevel + ", fileDownloadCount=" + fileDownloadCount + ", fileStatus=" + fileStatus
				+ "]";
	}
	
	
	
}

Controller

게시글(+파일) 등록(게시글과 thumbnail 이미지1개, images 이미지최대3개 등록가능)

게시글 등록

@RequestMapping("insert")
public String insertBoard(Board board, //커맨드 객체
		Model model, //session 접근용
        HttpServletRequest request, //파일 경로
        RedirectAttributes rdAttr, //리다이렉트 시 메세지 전달용
        @RequestParam(value="thumbnail", required=false)
        MultipartFile thumbnail,
        @RequestParam(value="images", required=false)
        List<MultiPartFile> images
        ) {
        
    // Session에서 회원 번호 얻어오기
    Member loginMember = (Member)model.getAttribute("loginMember");
    int boardWriter = loginMember.getMemberNo();
    
    // 회원 번호를 커맨드 객체 board에 저장(커맨드 객체 재활용)
    board.setBoardWriter(boardWriter+"");
    
    // 파일 저장 경로
    String root = request.getSession().getServletContext().getRealPath("resources");
    // 주소창 /springProject/resources 는 요청경로임
    // realPath는 webapp/resources 폴더
    
    String savePath = root + "/uploadFiles";
    
    // 저장 폴더 선택
    File folder = new File(savePath);
    
    // 만약 해당 폴더가 없는 경우 -> 폴더 만들기
    if(!folder.exists()) folder.mkdir();
    
    try {
    	// 전송된 파일 확인
        // @RequestParam을 이용하여 input type="file"
        // 파라미터를 얻어올 경우 값이 없을때는 value가 ""(빈문자열)이 전달됨
        
        // 썸네일 확인
        System.out.println("thumbnail :" + thumbnail.getOriginalFilename());
        
        // 이미지 업로드 확인
        for(int i=0; i<images.size(); i++) {
        	System.out.println("images[" + i + "] :"
            		+ images.get(i).getOriginalFilename());
        }
        
        // 업로드된 파일을 하나의 List에 저장
        List<Attachment> files = new ArrayList<Attachment>();
        Attachment At = null;
        
        // thumbnail 업로드 이미지 rename 작업 후 추가
        if(!thumbnail.getOriginalFilename().equals("")) {
        	// thumbnail이 등록된 경우
            
            // 파일명 rename
            String changeFileName = FileRename.rename(thumbnail.getOriginalFilename());
            
            // Attachment 객체 생성
            at = new Attachment(thumbnail.getOriginalFilename(),
            	changeFileName,
                savePath);
            
            // thumbnail의 fileLevel == 0
            at.setFileLevel(0);
            
            // files List에 추가
            files.add(at);
        }
        
        // images 업로드 이미지 rename 작업 후 추가
        for(MultipartFile mf : images) {
        	if(!mf.getOriginalFilename().equals("")) {
            	// image가 등록된 경우
                
                // 파일명 Rename
                String changeFileName = FileRename.rename(mf.getOriginalFilename());
                
                // Attachment 객체 생성
                at = new Attachment(mf.getOriginalFilename(),
                	changeFileName, savePath);
                
                // images의 fileLevel == 1
                at.setFileLevel(1);
                
                // files List에 추가
                files.add(at);
            }
        }
        
        // 게시글 + 이미지 삽입 Service 호출
        int result = boardService.insertBoard(board, files); 
        
        String msg = null;
        String url = null;
        
        if(result > 0) { // DB에 게시글 삽입 성공 시
        	
            // 서버에 파일 저장
            for(Attachment file = files) {
            	// 현재 접근한 파일이 썸네일이면
                if(file.getFileLevel() == 0 ) {
                	// file은 파일 정보 진짜 파일은 thumbnail임
                    thumbnail.transferTo(new File(file.getFilePath() + "/" 
                    	+ file.getFileChangeName()));
                    // transferTo() 가 정상 호출될 경우 파일이 저장됨
                } else { // 현재 접근한 파일이 일반 이미지라면
                	for(MultipartFile mf : images) {
                    	if(mf.getOriginalFileName().equlas(
                        		file.getFileOriginName()) ) {
                        	// mf: 실제 파일 자체
                            // at(file) : db에 저장하기 위한 파일 정보
                            // 두개를 비교해서 ""빈문자열(파일없을경우)걸러냄
                            mf.transferTo(new File(file.getFilePath()
                            + "/" + file.getFileChangeName()));
                            break;
                        }
                    }
                }
            } // end for
            
            msg = "게시글 등록 성공";
            // url = "detail?no="+result+"$currentPage=1";
            // 상세 조회 완성 후 사용
            
            url = "list";
            
        } else {
        	msg = "게시글 등록 실패";
            url = "list";
        }
        
        rdAttr.addFlashAttribute("msg", msg);
        return "redirect:" + url;
    
    } catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("errorMsg", "게시글등록과정에서오류");
			return "common/errorPage";
	}
        
}
    
    

 

'study > Spring' 카테고리의 다른 글

10_spring_(파일조회)  (0) 2020.03.12
9_Spring(파일업로드2)  (0) 2020.03.11
7_Spring(페이징)  (0) 2020.02.29
6_Spring(RedirectAttributes, ModelAndView)  (0) 2020.02.28
5_Spring(암호화)  (0) 2020.02.27