1-1. WebConfig.java
package com.icia.board.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
private String resourcePath = "/upload/**"; // html 에서 접근할 경로
private String savePath = "file:///D:/springboot_img/"; // 실제 파일이 저장된 경로
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(resourcePath)
.addResourceLocations(savePath);
}
}
기존 Spring Framework에서는 xml파일에 경로를 설정해 주었지만 Spring boot에서는 위와 같은 코드로 경로를 설정하였다.
1-2. BoardDTO.java
private MultipartFile boardFile;
private int fileAttached;
private String originalFileName;
private String storedFileName;
// 파일 여부에 따른 코드 추가
if (boardEntity.getFileAttached() == 1) {
boardDTO.setFileAttached(1);
boardDTO.setOriginalFileName(boardEntity.getBoardFileEntityList().get(0).getOriginalFileName());
boardDTO.setStoredFileName(boardEntity.getBoardFileEntityList().get(0).getStoredFileName());
} else {
boardDTO.setFileAttached(0);
}
파일여부에 따라 boardDTO의 fileAttached가 0 or 1로 지정했기때문에 그에따라 기본이름 , 변형이름들을 저장한다.
1-3. BoardService.java
@Transactional
public List<BoardDTO> findAll() {
List<BoardEntity> boardEntityList = boardRepository.findAll();
List<BoardDTO> boardDTOList = new ArrayList<>();
// for (BoardEntity boardEntity: boardEntityList) {
// boardDTOList.add(BoardDTO.toDTO(boardEntity));
// }
boardEntityList.forEach(boardEntity -> {
boardDTOList.add(BoardDTO.toDTO(boardEntity));
});
return boardDTOList;
}
@Transactional
public void updateHits(Long id) {
boardRepository.updateHits(id);
}
@Transactional
public BoardDTO findById(Long id) {
BoardEntity boardEntity = boardRepository.findById(id).orElseThrow(() -> new NoSuchElementException());
return BoardDTO.toDTO(boardEntity);
}
Spring boot에서는 부모 객체를 조회하면 자식 객체도 조회할 수 있기 때문에 각 메소드마다 @Transactional 어노테이션을 사용해야 한다.
1-4. boardDetail.html
<tr th:if="${board.fileAttached == 1}">
<th>image</th>
<td>
<img th:src="@{|/upload/${board.storedFileName}}" width="200" height="200" alt="">
</td>
</tr>
이미지가 올라갈 수 있도록 html에도 코드를 추가한다.
단일파일 이미지가 잘 올라오는 것을 볼 수 있다.
2-1 BoardDTO.java
private List<MultipartFile> boardFile;
private int fileAttached;
private List<String> originalFileName;
private List<String> storedFileName;
public static BoardDTO toDTO(BoardEntity boardEntity) {
BoardDTO boardDTO = new BoardDTO();
// 파일 여부에 따른 코드 추가
if (boardEntity.getFileAttached() == 1) {
boardDTO.setFileAttached(1);
// 파일 이름을 담을 리스트 객체 선언
List<String> originalFileNameList = new ArrayList<>();
List<String> storedFileNameList = new ArrayList<>();
// 첨부파일에 각각 접근
for (BoardFileEntity boardFileEntity : boardEntity.getBoardFileEntityList()) {
originalFileNameList.add(boardFileEntity.getOriginalFileName());
storedFileNameList.add(boardFileEntity.getStoredFileName());
}
boardDTO.setOriginalFileName(originalFileNameList);
boardDTO.setStoredFileName(storedFileNameList);
} else {
boardDTO.setFileAttached(0);
}
필드를 기본 String에서 List<String>으로 변경후 for문으로 리스트에 기본이름 , 변형이름을 저장한다.
2-2 BoardService.java
public Long save(BoardDTO boardDTO) throws IOException {
if (boardDTO.getBoardFile().get(0).isEmpty()) {
// 파일 없음
BoardEntity boardEntity = BoardEntity.toSaveEntity(boardDTO);
return boardRepository.save(boardEntity).getId();
public Long save(BoardDTO boardDTO) throws IOException {
BoardEntity boardEntity = BoardEntity.toSaveEntityWithFile(boardDTO);
BoardEntity savedEntity = boardRepository.save(boardEntity);
// 2. 파일이름 꺼내고, 저장용 이름 만들고 파일 로컬에 저장
for (MultipartFile boardFile: boardDTO.getBoardFile()) {
String originalFileName = boardFile.getOriginalFilename();
String storedFileName = System.currentTimeMillis() + "_" + originalFileName;
String savePath = "D:\\springboot_img\\" + storedFileName;
boardFile.transferTo(new File(savePath));
// 3. BoardFileEntity로 변환 후 board_file_table에 저장
// 자식 데이터를 저장할 때 반드시 부모의 id가 아닌 부모의 Entity 객체가 전달돼야 함.
BoardFileEntity boardFileEntity =
BoardFileEntity.toSaveBoardFileEntity(savedEntity, originalFileName, storedFileName);
boardFileRepository.save(boardFileEntity);
}
return savedEntity.getId();
}
}
마찬가지로 for문으로 각 기본이름 , 변형이름을 board_file_table에 저장한다.
자식 데이터를 저장할 때 반드시 부모의 id가 아닌 부모의 Entity 객체가 전달되어야 하는 중요점이 있다.
2-3 boardDetail.html
<tr th:if="${board.fileAttached == 1}">
<th>image</th>
<td th:each="fileName: ${board.storedFileName}">
<img th:src="@{|/upload/${fileName}}" width="200" height="200" alt="">
</td>
</tr>
마찬가지로 여러개니 th:if문으로 파일여부를 확인후 th:each문으로 이미지를 띄워주면 된다.
2-4 boardSave.html
<input type="file" name="boardFile" class="form-control" multiple>
저장하는 곳도 multiple 속성을 부여해야 한다.
'Spring > Spring boot icia 73일차' 카테고리의 다른 글
Spring boot Pk,FK 참조관계 맺기 (0) | 2023.06.07 |
---|---|
Spring boot interceptor(인터셉터) (0) | 2023.06.07 |
Spring boot 날짜 , builder , Modifying (0) | 2023.06.07 |
Spring boot 게시판 수정 , 삭제 (0) | 2023.06.07 |