[JAVA] 첨부파일 확장자 변경 후 파일 업로드시 변경 여부 체크

2023. 12. 4. 22:41웹/웹프로젝트

프로젝트를 진행중 사용자가 첨부파일 확장자를 변경 후 파일 업로드시 변경 여부를 체크해야할 일이 생겼다.

 

사용자가 exe,jsp 등의 첨부파일을 .jpg 등으로 바꾼 후 업로드하면 체크해야한다.

 

 

일반 자바를 이용하여 확장자를 잘라서 첨부파일 체크를 하는 경우 파일 확장자를 변경할시 알수가 없었다.

 

 

 

1. Apache Common IO

  apache common io 를 활용한 확장자 체크

1.pom.xml 추가

  	<dependencies>
        <dependency>   
           <groupId>commons-io</groupId>    
             <artifactId>commons-io</artifactId>  
                 <version>2.9.0</version>  
        </dependency>
       </dependencies>

 

2. 확장자 체크

 

        // 1. 확장자를 추출할 파일 준비     
		File file = new File("D:\\text.txt");
	      // 2. 파일 이름 확인        
		String fileName = file.getName();        
		// 3. 확장자 추출       
		String fileExtension = FilenameUtils.getExtension(fileName);        
		// 4. 결과 출력      
		System.out.println(fileExtension);  // txt

 

 

 

 

 

 

 

 

 

2. Apache Tick

아파치 티카를 이용하면 mime-Type 체크를 이용할 수 있다고 하여 사용해보았다.

 

   pom.xml 

pom.xml 2023-12-04 현재일 기준으로 사이트에서 최신버전을 사용했다.

https://tika.apache.org/1.26/gettingstarted.html

 

Apache Tika – Getting Started with Apache Tika

Getting Started with Apache Tika This document describes how to build Apache Tika from sources and how to start using Tika in an application. Getting and building the sources To build Tika from sources you first need to either download a source release or

tika.apache.org

<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-parsers</artifactId>
    <version>1.26</version>
  </dependency>
   <dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-core</artifactId>
    <version>1.26</version>
  </dependency>

 

 

 Test

 

 

      // 1. 확장자를 추출할 파일 준비     
		
		File file = new File("D:\\test\\testa.txt");
		

		Tika tika = new Tika();
		Metadata metadata = new Metadata();
		
		String mimeType="";
		
		try {
			mimeType = tika.detect(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		System.out.println(mimeType);

 

 

정상적으로 mime-type을 체크할 수 있었다.

이걸 이용해서 확장자가 변경되었는지 체크가 가능할까?

 

 

파일 원본의 mime-type을 체크하는 것이 아닌 현재의 mime-type을 체크할 수 있다면 변경 여부를 알 수 있지 않을까??

 

이러한 생각으로 JAVA의 파일 MIME-TYPE 을 확인할 수 있는지 여부를 체크했다.

 

 

 

 

3. JAVA의 파일  MIME-TYPE 확인 java.nio.file 활용

java.nio.file 을 활용하면 mime-type을 체크 할 수 있다는 정보를 찾은 후 java.nio.file을 활용해서 mime-type 체크를 진행해봤다.

 

		// 1. 확장자를 추출할 파일 준비     
		String mimeType="";
		Path source = Paths.get("D:\\test\\testa.txt");
		try {
			mimeType = Files.probeContentType(source);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("========================2 : " +mimeType);

 

 

실제로 결과가

text/plain 으로 나온것을 확인했다.이를 토대로 비교할 수 있는데

 

 

실제 파일은 video/quicktime 이지만 현재는 text/plain인것을 확인했다.

기존 파일로 바꾸면 두개가 일치할까? 기존의 mp4파일로 변경해보았다.

 

기존의 mp4파일로 변경하면

원본 mime-type은 달라지지만 현재 mime-type과 일치하는 것을 확인했다.

 

그러나 이상사항 발견

zip파일을 테스트하는 도중 아래와 같이 다르게 나오는것을 확인했다. 이걸로는 판별할 수 없다고 판단하여

========================1 : application/zip
========================2 : application/x-zip-compressed

 

 

mime-type용 화이트리스트를 작성하기로했다.

 

mime-type종류 참고

:https://www.htmlstrip.com/mime-file-type-checker

 

MIME File Type Checker - HTMLStrip

MIME File Type Checker A handy tool to check what type of file you are dealing with by checking the Multipurpose Internet Mail Extension. This is especially useful for developers who are working on validation and want to know if the file MIME type being te

www.htmlstrip.com

 

 

아래 소스에 위의 mime-type을 활용하여 붙여 넣어서 사용하도록 한다

	private boolean isAllowedMIMEType(String mimeType) {
	    String[] allowedMIMETypesEquals = {
	        "application/zip",    // .zip
	        "application/pdf",    // .pdf
	        "application/msword", // .doc, .dot
	        "application/x-hwp", "applicaion/haansofthwp", "application/x-tika-msoffice", // .hwp
	        "application/x-tika-ooxml"  // .xlsx, .pptx, .docx
	    };
	    for (int i=0; i<allowedMIMETypesEquals.length; i++) {
	        if (mimeType.equals(allowedMIMETypesEquals[i])) {
	            return true;
	        }
	    }
	    
	    String[] allowedMIMETypesStartsWith = {
	        "image",    // .png, .jpg, .jpeg, .gif, .bmp
	        "text",     // .txt, .html 등
	        "application/vnd.ms-word",          // .docx 등 워드 관련
	        "application/vnd.ms-excel",         // .xls 등 엑셀 관련
	        "application/vnd.ms-powerpoint",    // .ppt 등 파워포인트 관련
	        "application/vnd.openxmlformats-officedocument",    // .docx, .dotx, .xlsx, .xltx, .pptx, .potx, .ppsx
	        "applicaion/vnd.hancom"     // .hwp 관련
	    };
	    for (int i=0; i<allowedMIMETypesStartsWith.length; i++) {
	        if (mimeType.startsWith(allowedMIMETypesStartsWith[i])) {
	            return true;
	        }
	    }
	    
	    return false;
	}

 

 

 

 

 

 

반응형