Can't struts2 detect the content of a file? (Renaming extension trouble)

天大地大妈咪最大 提交于 2019-12-11 04:41:14

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/42792283/cant-struts2-detect-the-content-of-a-file-renaming-extension-trouble

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!