To identify the exact file content type, not go by extensions. Because there could be a scenario where file can be uploaded by changing the extesions.
eg: test.jpg file is renamed to test.jpg.txt - browser shows this file content type as text/plain. But the actual file is of image/jpeg.
This can be handled by below code:
eg: test.jpg file is renamed to test.jpg.txt - browser shows this file content type as text/plain. But the actual file is of image/jpeg.
This can be handled by below code:
import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; public class ActualContentType { public static void main(String[] args) throws Exception { Boolean status = isJPEG(new File("C:\\test.txt.jpg")); System.out.println("Status: " + status); } //http://www.filesignatures.net/index.php?page=search&search=FFD8FFE0&mode=SIG
private static Boolean isJPEG(File filename) throws Exception { DataInputStream ins = new DataInputStream(new BufferedInputStream(new FileInputStream(filename))); try { if (ins.readInt() == 0xffd8ffe0) { return true; } else { return false; } } finally { ins.close(); } } }