1005 Spring file

onnbi·2022년 11월 28일
0
post-thumbnail

sts에서 첨부파일 올리기

insert

  1. fileRename 객체를 만든다
package common;

import java.io.File;

import org.springframework.stereotype.Component;

@Component
public class FileRename {

	public String fileRename(String path, String filename) {
		// 파일 중복이름 체크 메서드
		// 최종적으로 사용할 파일 path를 돌려주는 클래스
		// 첫번째 매개변수 : upload다음에 올 파일명
		
		String onlyFilename = filename.substring(0, filename.lastIndexOf("."));
      	 // onlyFilename=test (test.txt)
		String extention = filename.substring(filename.lastIndexOf("."));	// .txt
		
		// 실제 업로드할 파일 명
		String filepath = null;
		// 파일명이 중복되는 경우 뒤에 붙일 숫자
		int count = 0;
		while(true) {
			if(count==0) {
				// 파일이름체크 첫번째인 경우
				filepath = onlyFilename+extention;
				
			}else {
				filepath = onlyFilename+"_"+count+extention;
			}
			File checkFile = new File(path+filepath);
			if(!checkFile.exists()) {
				// 중복파일명이 아닌 경우 무한 반복문 나가기
				break;
			}
			count++;
		}
		return filepath;
	}
}
  1. 보내는 파일은 multipart/form-data / multiple
  1. controller 작성
@RequestMapping(value="/boardWrite2.do")
	public String boardWrite2(Board b, MultipartFile[] boardFile, HttpServletRequest request) {
		// 파일 목록을 저장할 리스트 생성
		ArrayList<FileVo> list = new ArrayList<FileVo>();
		// MultipartFile[]은 jsp에서 첨부한 파일 갯수만큼 길이가 생성
		// 단, 첨부파일을 한 개도 첨부하지 않아도 배열의 길이는 기본적으로 1
		
		if(!boardFile[0].isEmpty()) {
         // 첨부파일이 없는 경우 배열 첫번째 인덱스의 value 비어있음 > 있는 경우로 할 것임 !
		
          // 1. 파일업로드 경로 설정 (getRealPath()까지가 webapp)
          String savePath = request.getSession().getServletContext().getRealPath("/resources/upload/board/");
			
		// 2. 반복문을 이용한 파일 업로드
		for(MultipartFile file : boardFile) {
		// 파일명이 기존업로드한 파일명과 중복되는 경우
         // 기존파일을 삭제하고 새파일 남는 현상(덮어쓰기)
		// = 파일명 중복처리
				
		// 2-1 사용자가 업로드한 파일 이름 추출
		String filename = file.getOriginalFilename();	// filename=test.txt라는 값을 추출
		String filepath = fileRename.fileRename(savePath, filename);
				
			
          // 중복처리가 끝난 파일명으로 파일업로드 진행
          try {
            
            FileOutputStream fos = new FileOutputStream(new File(savePath+filepath));
          // 속도를 개선하기 위한 보조스트림
            BufferedOutputStream bos = new BufferedOutputStream(fos);

            try {
              byte[] bytes = file.getBytes();
              bos.write(bytes);
              bos.close();
            } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            } //피일업로드

          } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          // 파일 업로드 끝
          FileVo fileVo = new FileVo();
          fileVo.setFilename(filename);
          fileVo.setFilepath(filepath);
          list.add(fileVo);
        }

        }

      // 데이터 베이스에 insert - 비즈니스 로직
      int result = service.insertBoard2(b, list);
      // 성공실패 구분
      // 성공 == result == list.size()+1
      return "redirect:/boardList.do";
 }

update 추가 예정.

profile
aelatte coding journal

0개의 댓글