web developer

[java] 파일 확장자 필터링 본문

Language/Java

[java] 파일 확장자 필터링

trueman 2023. 12. 13. 21:18
728x90
728x90

파일 확장자를 제한하는, 필터링하는 기능을 하는 클래스이다.

허용되지 않은 확장자명을 파라메터로 받아오는 경우에는 예외를 발생시킨다.

 

java
package board.cmmn;
import javax.servlet.ServletException;

public class ExtUtil {
	public static String allowExt(String value) {
		String fileExtNm = "";
		try {
			if(value != null || value.equals("")) {
				String fileExt = "";
				if(value.contains(".")) { // 파일이름 +확장자명
					fileExt = value.substring(value.lastIndexOf(".") + 1, value.length());
					fileExt = fileExt.toLowerCase();
				}else { // 확장자
					fileExt = value.toLowerCase();
				}
				
				// 허용되지 않는 확장자명 
				String notAllowExt[] = {"jsp","jspx","asp","class","php","pdb","html","exe","vbs","bet","dll"};
				for(int i=0; i<notAllowExt.length; i++) {
					if(fileExt.equals(notAllowExt[i])) {
						fileExtNm = "";
						throw new ServletException("허용되지 않은 확장자명입니다.");
					}
				}
				
				// 이미지 파일
				String allowImgExt[] = {"jpg","jpeg","gif","png","bmp"};
				for(int i=0; i<allowImgExt.length; i++) {
					if(fileExt.equals(allowImgExt[i])) {
						fileExtNm = "";
						fileExtNm = fileExt;
					}
				}
				
				// 문서 파일
				String allowDocExt[] = {"xls","xlsx","csv","pdf","hwp","doc","docx","ppt","pptx","zip"};
				for(int i=0; i<allowDocExt.length; i++) {
					if(fileExt.equals(allowDocExt[i])) {
						fileExtNm = "";
						fileExtNm = fileExt;
					}
				}
				
				// 음악/영상파일
				String allowVideoExt[] = {"mp3","mp4"};
				for(int i=0; i<allowVideoExt.length; i++) {
					if(fileExt.equals(allowVideoExt[i])) {
						fileExtNm = "";
						fileExtNm = fileExt;
					}
				}
			}
			
		}catch(ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBoundsException");
		}catch(IllegalArgumentException e) {
			System.out.println("IllegalArgumentException");
		} catch (ServletException e) {
			System.out.println("ServletException");
		}
		
		return fileExtNm;
	}
}

 

 

728x90
728x90
Comments