반응형
파일 업로드 기능
1. signUp.jsp 파일 업로드 기능 추가
2. dto 파일 수정 - MultipartFile file 에 대한 개념
3. Define.java 파일 최대 크기 설정 후 yml 파일 수정
1. signUp.jsp 코드 수정 (파일 업로드 기능 추가)
signUp.jsp
1 2 3 4 | <div class="custom-file"> <input type="file" class="custom-file-input" id="customFile"> <label class="custom-file-label" for="customFile">Choose file</label> </div> | cs |
1 2 3 4 5 6 7 8 9 10 | <form action="/user/sign-up" method="post" enctype="multipart/form-data"> <input type="file" class="custom-file-input" id="customFile" accept=".jpg, .jpeg, .png"> <script> $(".custom-file-input").on("change", function() { var fileName = $(this).val().split("\\").pop(); $(this).siblings(".custom-file-label").addClass("selected").html(fileName); }); </script> | cs |
→ enctype="multipart/form-data" 코드, 스크립트 코드 추가
2. dto 파일 수정 - MultipartFile file 에 대한 개념
SignUpFormDto.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | package com.tenco.bank.dto; import org.springframework.web.multipart.MultipartFile; import lombok.Data; @Data public class SignUpFormDto { private String username; private String password; private String fullname; // 다중 처리는 배열[]로 사용하자. private MultipartFile file; // file은 name file 속성과 일치시켜야 함. // 원래 이미지 명, 실제 업로드 된 이미지 명 private String originFileName; private String uploadFileName; } | cs |
→ MultipartFile 선언하기
3. 파일 최대 크기 yml 파일 수정
Define.java
1 2 3 4 5 6 7 8 9 10 11 12 13 | package com.tenco.bank.utils; public class Define { // 서버 프로그램에서 상태값을 변경할 수 있는 변수는 절대 지양 public final static String PRINCIPAL = "principal"; // 이미지 처리 관련 public final static int MAX_FILE_SIZE = 1024 * 1024 * 20; // 최대 20MB // 1byte // 1024 -> 1KB // 1,048,576 -> 1MB (1024 * 1024) } | cs |
→ 이미지 사이즈 지정
application.yml
spring:
mvc:
view:
prefix: /WEB-INF/view/
suffix: .jsp
servlet:
multipart:
max-file-size: 20MB #최대 20MB(MaxUploadSizeExceedException 발생)
max-request-size: 20MB
→ yml 파일 - multipart 이미지 사이즈 지정
UserController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | @PostMapping("/sign-up") public String signUpProc(SignUpFormDto signUpFormDto) { // 사용자 프로필 이미지는 옵션 값으로 설정할 예정 MultipartFile file = signUpFormDto.getFile(); if(file.isEmpty() == false) { if(file.getSize() > Define.MAX_FILE_SIZE) { throw new CustomRestfullException("파일 크기가 20MB 이상일 수 없습니다.", HttpStatus.BAD_REQUEST); } try { // 파일 저장 기능 구현 - 업로드 파일은 HOST 컴퓨터 다른 폴더로 관리 String saveDirectory = Define.UPLOAD_DIRECTORY; // 파일 생성시 폴더가 없다면 오류 발생 File dir = new File(saveDirectory); if (dir.exists() == false) { dir.mkdirs(); // 폴더가 없으면 폴더 생성 } UUID uuid = UUID.randomUUID(); // 밑에 형식으로 폴더에 들어감 String fileName = uuid + "_" + file.getOriginalFilename(); // 전체 경로 지정 String uploadPath = Define.UPLOAD_DIRECTORY + File.separator + fileName; File destination = new File(uploadPath); // 업로드한 파일을 로컬 저장소에 저장하는 방법 file.transferTo(destination); // 따로 구분 // 객체 상태 변경(dto) signUpFormDto.setOriginFileName(file.getOriginalFilename()); signUpFormDto.setUploadFileName(fileName); } catch(Exception e) { e.printStackTrace(); } } | cs |
리소스 처리
경우의 수 생각해보기
1. 회원가입시 이미지 등록 안 하는 경우
2. 회원가입시 이미지 등록 하는 경우
3. 로그인 하지 않았을 경우
WebMvcConfig.java
- addResourceHandler 등록하기
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | @Configuration public class WebMvcConfig implements WebMvcConfigurer { // 리소스 등록 처리 // 서버 컴퓨터에 위치한 Resource를 활용하는 방법 (프로젝트 외부 폴더 접근 방법) // c드라이버에 있는 spring_upload 폴더에 접근해야 한다. @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 서버에서 쓸 패턴 지정 // 코드 상에서 /images/uploads/ 쓰면 // file://C:\\spring_upload\\bank\\upload/ 찾아감 registry.addResourceHandler("/images/uploads/**") .addResourceLocations("file:///C:\\spring_upload\\bank\\upload/"); } } | cs |
jsp 활용
1 2 3 4 5 6 7 8 9 10 | <%-- 사용자 이미지 or 사용자 이미지 등록 안 함 --%> <%-- WebMvcConfig에 등록한 addResource.. 사용하기 --%> | cs |
반응형
'프로그래밍 > Spring Boot' 카테고리의 다른 글
Spring Boot_MyBatis if문(동적 쿼리 생성) 사용하기 (0) | 2023.05.07 |
---|---|
Spring Boot_ 시간 포맷 기능, 금액 단위 포맷 기능 (0) | 2023.05.05 |
Spring Boot_javax.el.PropertyNotFoundException (0) | 2023.04.24 |
Spring Boot_암호화 처리 (0) | 2023.04.21 |
Spring Boot_마이그레이션(migration) H2 데이터베이스 → MySQL 데이터베이스 (0) | 2023.04.21 |