In my application we are uploading image/audio/video files. I have allowed some fixed set of allowed extensions of each types. If the extension does not match the list of provided extensions then it won't upload, but if the user renames the .exe, .pdf file to .jpg or .png the it would clear the UI validations and servlet will be called and upload will happen. But later that would cause a problem.
Is there any way to check the same at backend and then throw an Exception accordingly.
I have tried using :
import java.net.*;
public class FileUtils{
public static String getMimeType(String fileUrl) throws java.io.IOException {
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String type = fileNameMap.getContentTypeFor(fileUrl);
return type;
}
public static void main(String args[]) throws Exception {
System.out.println(FileUtils.getMimeType("file:/home/kavinder/file.pdf"));
// this is a .jpg file renamed to .pdf
}
}
This is returning according to extension only. And
import javax.activation.MimetypesFileTypeMap;
import java.io.File;
class GetMimeType {
public static void main(String args[]) {
File f = new File("/home/kavinder/file.jpg");
System.out.println("Mime Type of " + f.getName() + " is " + new MimetypesFileTypeMap().getContentType(f));
}
}
This is always returning the mime type as: application/octet-stream
Thank you in advance