개발/JAVA & Spring

이미지 파일의 판단 :: checkImageType(File file)

까망군 2018. 11. 30. 20:34

파일이 이미지 타입인지 확인하기 위해 Files.probeContentType() 사용하여 메소드를 만들었으나 이미지 파일인데도 false 를 반환하였다.

    private boolean checkImageType(File file){
        try{
            String contentType = Files.probeContentType(file.toPath());

            return contentType.startsWith("image");
        } catch(IOException e){
            e.printStachTrace();
        }
        return false;
    }

디버그를 해보니 Files.probeContentType() 가 null 을 반환하여 false 가 리턴됨.
해결책을 찾기 위해 검색을 해봤으니 버그라고 한다. 

https://stackoverflow.com/questions/12407479/why-does-files-probecontenttype-return-null

JAVA 8 에서는 해결될거라고 하는데 ㅡ.ㅡ JAVA 8 사용중임


다른 해결책으로 Files.probeContentType() 을 사용하는 대신
jMimeMagic 이나 Tika 를 사용할 수 있는 것을 알게 되었다.

https://www.baeldung.com/java-file-mime-type

코드를 다음과 같이 수정한다.

    private boolean checkImageType(File file){
        Magic magic = new Magic();
        try {
            MagicMatch match = magic.getMagicMatch(file, false);
            return match.getMimeType().contains("image");
        } catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }