Spring/SpringBoot

[SpringBoot] 간단한 게시판 생성_첨부파일 업로드

코딩맛 2024. 1. 15. 17:31

1. 게시판 파일 업로드

1) 데이터베이스 내 column 추가 - filename, filepath

 

2) entity

private String filename;

private String filepath;

public String getFilename() {
        return filename;
}

public void setFilename(String filename) {
    this.filename = filename;
}

public String getFilepath() {
    return filepath;
}

public void setFilepath(String filepath) {
    this.filepath = filepath;
}

추가한 column에 대한 entity 변수 정의

 

3) view (html)

boardwrite.html

<div class="layout">
    <form action="/board/writedo" method="post" enctype="multipart/form-data">
        <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Name</label>
            <input id="exampleFormControlInput1" name="title"  type="text"><br>
        </div>
        <div class="mb-3">
            <label for="exampleFormControlTextarea1" class="form-label">Example textarea</label><br>
            <textarea id="exampleFormControlTextarea1" name="content"></textarea>
        </div>
        <input type="file" name="file">
        <button type="submit">작성</button>
    </form>
</div>

mutipart 선언과 파일 업로드 input 박스 추가

 

4) service

 public void write(Board board, MultipartFile file) throws Exception{

    String projectPath = System.getProperty("user.dir") + "/src/main/resources/static/files";

    UUID uuid = UUID.randomUUID();

    String fileName = uuid + "_" + file.getOriginalFilename();

    File saveFile = new File(projectPath, fileName);

    file.transferTo(saveFile);

    board.setFilename(fileName);
    board.setFilepath("/files/" + fileName);

    boardRepository.save(board);

}

projectPath : 저장경로 지정

uuid : 파일 이름에 붙일 랜덤 이름 생성

filename : 랜덤이름을 파일 네임 앞에 붙이고 파일이름으로 파일명 생성

saveFile : 파일을 생성하는데 projectPath에 담고, name이름으로 담기는 의미

file.transferTo() : 예외처리 필요하므로 throw 이용

 

board.setFilename(fileName); 
board.setFilepath("/files/" + fileName);

-> 데이터를 넣기 위해 filename과 filepath를 set해준다.

 

5) controller

@PostMapping("/board/writedo")
public String boardWritePro(Board board, Model model, MultipartFile file) throws Exception{
    boardService.write(board, file);

    model.addAttribute("message", "글 작성이 완료되었습니다.");
    model.addAttribute("searchUrl","/board/list");

    return "message";
}
@PostMapping("/board/update/{id}")
public String boardUpdate(@PathVariable("id") Integer id, Board board, Model model, MultipartFile file) throws Exception{

    Board boardTemp = boardService.boardView(id);
    boardTemp.setTitle(board.getTitle());
    boardTemp.setContent(board.getContent());

    boardService.write(boardTemp, file);

    model.addAttribute("message", "글 수정이 완료되었습니다.");
    model.addAttribute("searchUrl","/board/list");

    return "message";
}

메소드 매개변수로 file 변수를 받고 예외처리도 해줌

.write() 메소드 매개변수에도 file을 추가해줌

 

6) view (html)

boardview.html

<body>
<h1 th:text="${board.title}">제목입니다.</h1>
<p th:text="${board.content}">내용이 들어갈 부분입니다.</p>
<a th:href="@{${board.filepath}}">다운받기</a>
<a th:href="@{/board/delete(id=${board.id})}">글 삭제</a>
<a th:href="@{/board/modify/{id}(id=${board.id})}">글 수정</a>
</body>

다운받기 버튼을 우르면 이미지가 있는 경로에 가서 이미지 보여줌

 

 

https://minddokddok.tistory.com/34?category=1040940

 

스프링 부트(Spring Boot)로 간단한 게시판 만들기 - 4

이전 단계였던 게시물 삭제 기능 구현에 이어, 게시물 수정을 해보도록 하자 6) 게시물 수정 - 게시물 수정 페이지 생성 우선, 게시물 수정 버튼을 만들어주자. view부분에 넣어줘야하기에 boardview.

minddokddok.tistory.com

위 해당글을 참고하였습니다.