Spring Boot Board Project_15 업로드 파일 목록

송지윤·2024년 4월 21일
0

Spring Framework

목록 보기
48/65

1. 사이드바 업로드 파일 목록 클릭했을 때 요청 받아줄 Controller 필요

<a href="/myPage/fileList">업로드 파일 목록</a>

Controller

	@GetMapping("fileList")
	public String fileList(Model model) {
		
		// 파일 목록 조회 서비스 호출
		List<UploadFile> list = service.fileList();
		
		// model 에 list 담기
		model.addAttribute("list",list);
		
		// model list 담아서 /myPage/myPage-fileList 여기로 보내줄 거임
		return "myPage/myPage-fileList";
	}

2. Service 에서 mapper.xml 호출해서 list 반환

ServiceImpl

	@Override
	public List<UploadFile> fileList() {
		return mapper.fileList();
	}

mapper.xml

	<select id="fileList">
		SELECT FILE_NO, FILE_PATH, FILE_ORIGINAL_NAME, FILE_RENAME, MEMBER_NICKNAME,
		TO_CHAR(FILE_UPLOAD_DATE, 'YYYY-MM-DD') FILE_UPLOAD_DATE
		FROM "UPLOAD_FILE"
		JOIN "MEMBER" USING (MEMBER_NO)
		ORDER BY FILE_NO DESC
	</select>

3. 돌려받은 값 html 화면 보여주기

myPage-fileList.html

        <table border="1" style="border-collapse: collapse;">
          <thead>
            <tr>
              <th>번호</th>
              <th>파일명</th>
              <th>업로드 회원</th>
              <th>업로드 날짜</th>
              <th>이미지</th>
            </tr>
          </thead>

          <tbody>
            <tr th:each="file : ${list}" th:object="${file}">

              <td th:text="*{fileNo}">파일 번호</td>

              <td>
                <!-- href 경로 : /myPage/file/20240421155238_00001.png -->
                <a th:href="|*{filePath}*{fileRename}|"
                  th:download="*{fileOriginalName}"
                  th:text="*{fileOriginalName}">파일명</a>
              </td>

              <td th:text="*{memberNickname}">업로드 회원</td>

              <td th:text="*{fileUploadDate}">업로드 날짜</td>
			  
              <td>
                <img th:src="|*{filePath}*{fileRename}|" alt="이미지" height="100px">
              </td>
			      </tr>
			    </tbody>

        </table>

파일 여러 개 업로드

html

        <form action="/myPage/file/test3" method="post" enctype="multipart/form-data">
          <h3>여러 파일 업로드</h3>

          <pre>
            1) 같은 name 속성을 가지는 type="file"
               요소를 여러 개 작성
            
            2) multiple 속성 이용
          </pre>

          <div>
            1번) type="file" 요소를 여러 개 작성
            <br>
            <input type="file" name="aaa">
            <br>
            <input type="file" name="aaa">
          </div>

          <hr>

          <div>
            2번) multiple 사용(드래그 가능)
            <input type="file" name="bbb" multiple>
          </div>

          <button>제출하기</button>

        </form>

1. 요청 받아줄 Controller service 호출

	@PostMapping("file/test3")
	public String fileUpload3(
			@RequestParam("aaa") List<MultipartFile> aaaList,
			@RequestParam("bbb") List<MultipartFile> bbbList,
			@SessionAttribute("loginMember") Member loginMember,
			RedirectAttributes ra
			) throws Exception {
		
		// aaa 파일 미제출 시 (input 창이 두개)
		// -> 0번, 1번 인덱스 파일이 모두 비어있음
		
		// bbb (multiple) 파일 미제출 시
		// -> 0번 인덱스 파일이 비어있음
		
		int memberNo = loginMember.getMemberNo();
		
		// result == 업로드한 파일 개수
		int result = service.fileUpload3(aaaList, bbbList, memberNo);

2. Service List 에 들어간 값에 따라 처리

	@Override
	public int fileUpload3(List<MultipartFile> aaaList, List<MultipartFile> bbbList, int memberNo) throws Exception {

		// 1. aaaList 처리
		int result1 = 0;
		
		// 업로드된 파일이 없을 경우를 제외하고 업로드
		for(MultipartFile file : aaaList) {
			
			if(file.isEmpty()) {
				continue;
				// 현재 접근한 파일이 isEmpty 면 다음 파일로 넘어가겠다.
			}
			
			// fileUpload2() 메서드 호출 (재활용)
			// -> 파일 하나 업로드 + DB INSERT
			result1 += fileUpload2(file, memberNo);
		}
		
		// 2. bbbList 처리
		int result2 = 0;
		
		// 업로드된 파일이 없을 경우를 제외하고 업로드
		for(MultipartFile file : bbbList) {
			
			if(file.isEmpty()) {
				continue;
				// 현재 접근한 파일이 isEmpty 면 다음 파일로 넘어가겠다.
			}
			
			// fileUpload2() 메서드 호출 (재활용)
			// -> 파일 하나 업로드 + DB INSERT
			result2 += fileUpload2(file, memberNo);
		}		
		
		return result1 + result2;
	}

3. Controller 로 돌아온 result 값에 따라 처리

		String message = null;
		
		if(result == 0) {
			message = "업로드된 파일이 없습니다.";
		} else {
			message = result + "개의 파일이 업로드 되었습니다.";
		}
		
		ra.addFlashAttribute("message", message);
		
		return "redirect:/myPage/fileTest";

출력 결과

0개의 댓글