Issue
How to not hardcoding image extensions in Java?
switch(extension) {
case "zip" -> {
FileUtil.saveFile(multipartFile, historyFolder, FileType.ZIP, backupFilePath);
FileUtil.saveFile(multipartFile, target, FileType.ZIP, filePath);
}
case "jpg", "jpeg", "png", ".bmp", ".svg", "webp", "jfif", "pjpeg", "pjp", "apng", "avif" -> {
FileUtil.saveFile(multipartFile, historyFolder, FileType.IMAGE, backupFilePath);
FileUtil.saveFile(multipartFile, target, FileType.IMAGE, filePath);
}
default -> throw new GlobalCustomException(ErrorCode.ILLIGAL_FILE_TYPE);
}
Above is my code.
In the case statement, I have listed strings as hard-coded as jpg, jpeg....
This code is not flexible, so I'm sure there must be a better way.
I'd appreciate it if you could give me a solution that I'm not aware of.
Solution
As one of possible ways, you can use URLConnection.guessContentTypeFromName()
like this.
String mimeType = java.net.URLConnection.guessContentTypeFromName("test." + extension);
boolean isImage = mimeType != null && mimeType.startWith("image/")
You can add custom extensions to the $JAVA_HOME/jre/lib/content-types.properties
file.
Also see these questions.
Answered By - relent95
Answer Checked By - Pedro (JavaFixing Volunteer)