Springboot

[Springboot] 37. 파일 확장자 인증 검사

Song hyun 2024. 8. 14. 11:15
728x90
반응형

[Springboot] 37. 파일 확장자 인증 검사

 

UserService에 하단의 코드를 작성하게 될 경우, image(gif, jpg, jpeg, png) 형식 외의 파일을 넣으면 예외처리 된다.

 

위와 같이 service 클래스에서 이미지 외의 파일은 거부할 수 있게 코드를 작성해보자.

 

1. 백엔드에서 파일 확장자 검사

int index=mFile.getOriginalFilename().lastIndexOf(".");
		if(index>0) {
			String extension = filename.substring(index+1);
			System.out.println("파일 확장자 명 : "+extension);
			System.out.println("1번 테스트 : "+extension.equals("png"));
			System.out.println("2번 테스트 : "+extension.equals("jpg"));
			System.out.println("3번 테스트 : "+extension.equals("jpeg"));
			if(!extension.equals("png") && !extension.equals("jpg") && !extension.equals("jpeg")) {
				throw new DataDeliveryException("파일 형식이 잘못되었습니다.", HttpStatus.INTERNAL_SERVER_ERROR);
			}
		}
// 코드 수정
		// getAbsolutePath() : 파일 시스템의 절대 경로를 나타냅니다.
		// (리눅스 또는 MacOS)에 맞춰서 절대 경로가 생성시킬 수 있다!
		//String saveDirectory = new File(uploadDir).getAbsolutePath();
		String saveDirectory = uploadDir;
		System.out.println("saveDirectory : "+saveDirectory);
		
		String filename = mFile.getOriginalFilename();
		
		// 파일 이름 생성 (파일명 중복 예방)
		String uploadFileName = UUID.randomUUID()+"_"+filename;
		
		int index=mFile.getOriginalFilename().lastIndexOf(".");
		if(index>0) {
			String extension = filename.substring(index+1);
			System.out.println("파일 확장자 명 : "+extension);
			System.out.println("1번 테스트 : "+extension.equals("png"));
			System.out.println("2번 테스트 : "+extension.equals("jpg"));
			System.out.println("3번 테스트 : "+extension.equals("jpeg"));
			if(!extension.equals("png") && !extension.equals("jpg") && !extension.equals("jpeg")) {
				throw new DataDeliveryException("파일 형식이 잘못되었습니다.", HttpStatus.INTERNAL_SERVER_ERROR);
			}
		}
		
		// 파일 전체 경로 + 새로 생성한 파일명
		String uploadPath = uploadDir+uploadFileName;
		System.out.println("------------------------------");
		System.out.println(uploadPath);
		System.out.println(uploadFileName);
		System.out.println("------------------------------");
		File destination = new File(uploadPath);
		
		// 반드시 수행
		try {
			mFile.transferTo(destination);
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
			throw new DataDeliveryException("파일 업로드 중에 오류가 발생했습니다.", HttpStatus.INTERNAL_SERVER_ERROR);
		}
		
		return new String[] {mFile.getOriginalFilename(), uploadFileName};
	}

 

 

2. 프론트엔드(HTML)에서 파일 확장자 검사 (<img accept> 사용)

HTML에서 <img> - accept 속성을 사용하게 될 경우, 파일 선택 창에서 image 형식의 파일들과 폴더만 선택할 수 있게 된다.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!-- header.jsp  -->
<%@ include file="/WEB-INF/view/layout/header.jsp"%>

<!-- start of content.jsp(xxx.jsp)   -->
<div class="col-sm-8">
	<h2>회원 가입</h2>
	<h5>Bank App에 오신걸 환영합니다</h5>
	
	<form action="/user/sign-up" method="post" enctype="multipart/form-data"> 
		<div class="form-group">
			<label for="username">username:</label>
			<input type="text" class="form-control" placeholder="Enter username" id="username" name="username" value="야스오1"  >
		</div>
		<div class="form-group">
			<label for="pwd">Password:</label>
			<input type="password" class="form-control" placeholder="Enter password" id="pwd" name="password" value="asd123">
		</div>
		<div class="form-group">
			<label for="fullname">fullname:</label>
			<input type="text" class="form-control" placeholder="Enter fullname" id="fullname" name="fullname" value="바람검객">
		</div>
		 <div class="custom-file">
    	  <input type="file" class="custom-file-input" id="customFile" name="mFile"
    	  accept="image/*">
      	  <label class="custom-file-label" for="customFile">Choose file</label>
     	</div>
		<div class="d-flex justify-content-end">
			<button type="submit" class="btn btn-primary mt-md-4">회원가입</button>
		</div>
	</form>


</div>
<!-- end of col-sm-8  -->
</div>
</div>
<!-- end of content.jsp(xxx.jsp)   -->

<script>
// Add the following code if you want the name of the file appear on select
$(".custom-file-input").on("change", function() {
  var fileName = $(this).val().split("\\").pop();
  $(this).siblings(".custom-file-label").addClass("selected").html(fileName);
});
</script>

<!-- footer.jsp  -->
<%@ include file="/WEB-INF/view/layout/footer.jsp"%>
728x90
반응형