파일 업로드를 위한 초기 예제

<body>

  <h1>파일 업로드 예제</h1>

  <form action="/upload/file" method="post" enctype="multipart/form-data">
    <input type="file" name="thumbnail" id="img-input" accept="image/*" multiple>
    <button type="submit">전송</button>
  </form>

</body>
@Controller
@Slf4j
public class UploadController {

    // mkdir 폴더 만들고 업로트할 루트 경로
    private String rootPath = "D:/spring-prj/upload";

    @GetMapping("/upload/form")
    public String uploadForm() {
        return "upload/upload-form";
    }

    @PostMapping("/upload/file")
    // jsp 에 업로드 @RequestParam name , 여러 파일 받을거면 multi 파람 추가 !
    public String uploadFile(@RequestParam("thumbnail") MultipartFile file) {
        log.info("file-name: {}", file.getOriginalFilename()); //file-name: logo.png
        log.info("file-size: {}MB", file.getSize()/1024.0 / 1024.0);  //file-size: 0.010786056518554688MB
        log.info("file-type: {}", file.getContentType()); //file-type: image/png

        // 첨부파일 서버에 저장하기
        // 📌1. 루트 디렉토리를 생성 new File();
        File root = new File(rootPath);
        if (!root.exists())
            root.mkdirs();  // 첨부파일 존재하지 않을 시 만들어라

        FileUtil.uploadFile(rootPath, file);

        // 📌2. 첨부파일의 경로를 만들어서 파일 객체로 포장
//        File uploadFile = new File(rootPath, file.getOriginalFilename());

        // 📌3. MultipartFile 객체로 저장명령 - 전송 transferTo(file);
//        try {
//            file.transferTo(uploadFile);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        return "redirect:/upload/form";
    }

}
public class FileUtil {

    /**
     * ⭐ 사용자가 클라이언트에서 파일을 전송했을 때
     * 중복이 없는 새로운 파일명을 생성하여 해당 파일명으로
     * 날짜별 폴더로 업로드하는 메서드
     *
     * @param file - 사용자가 업로드한 파일의 정보객체
     * @param rootPath - 서버에 업로드할 루트 디렉토리 경로
     *                   ex) D:/spring-prj/upload
     * @return - 업로드가 완료되었을 경우 업로드 된 파일의 위치 경로
     *                   ex)  /2024/06/05/djfalsjdflaksjlfdsaj_고양이.jpg
     */
    public static String uploadFile(String rootPath, MultipartFile file) {

        // 원본 파일명을 중복이 없는 랜덤 파일명으로 변경
        // ⭐⭐ UUID.randomUUID() - 중복 없는 랜덤 문자를 생성해주는
        String newFileName = UUID.randomUUID() + "_" + file.getOriginalFilename();

        // 파일 업로드 수행
        try {
            file.transferTo(new File(rootPath, newFileName));
        } catch (IOException e){
            e.printStackTrace();
        }

        return "";
    }
}

회원가입 - 프로필 사진 파일 업로드

회원가입 sing-up 과 연결된 부분 다 추가 수정하기

SingUpDto, MemberCotroller, Sign-up.jsp js ..