Reputation: 55
We have an application done with struts2. We limited the uploaded files to microsoft documents and acrobat pdf. All go fine. But when a user change the extension of the file, struts 2 is unable to detect that change and accept the file.
For example logo.png -> logo.pdf
Our configuration in the struts2 file is like this:
<interceptor-ref name="interceptorFileStack">
<param name="fileUpload.allowedTypes">application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document</param>
<param name="fileUpload.allowedExtensions">.pdf,.docx,.doc</param>
<param name="fileUpload.maximumSize">4194304</param>
</interceptor-ref>
I thought that allowedExtensions control the extension, and allowedTypes the content of the file...
Anyway to detect that change of the extension only with struts 2? Or i need another library? Any recommendation?
Upvotes: 1
Views: 315
Reputation: 654
Most of the time the MIME-Type sent by the browser is derived by the file extension. Thus a renamed jpg->pdf is a "application/pdf" filetype.
If you can't trust your users and have to confirm the correct data type you have to use something like Apache Tika or JHOVE
A small example for Tika would be:
Path path = Paths.get("myfile.txt");
TikaConfig tika = new TikaConfig();
Metadata metadata = new Metadata();
metadata.set(Metadata.RESOURCE_NAME_KEY, path.toString());
String mimetype = tika.getDetector().detect(TikaInputStream.get(path), metadata).toString();
System.out.println("File " + path + " is " + mimetype);
(from the tutorial)
JHOVE is mainly a gui/commandline tool you can use, but it should also be possible to use this via an API.
Upvotes: 2