简体   繁体   English

Java中的分段文件上传检查MIME类型

[英]multipart file upload check mime type in java

I am using mimeutil for checking the mimetype of a file. 我正在使用mimeutil检查文件的mimetype。 And only allowing csv and json files. 并且仅允许csv和json文件。 But getting this mimetype for a json file "application/x-ipynb+json" mime type which is nowhere found. 但是为找不到文件的json文件“ application / x-ipynb + json” mime类型获取此mimetype。 Any help will be appreciated to get the exact mime type of a file if also renamed a exe file to json which should not be allowed for security reasons. 如果也将exe文件重命名为json,则出于帮助获取确切的mime类型的文件,出于安全原因,我们将不胜感激。 Refer below code for reference: 请参考以下代码以供参考:

public static String verifyExtension(MultipartFile File){
String mimeType = null;
        MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
        MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.ExtensionMimeDetector");
        //MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.OpendesktopMimeDetector");
        MimeUtil.registerMimeDetector(System.getProperty("os.name").startsWith(
              "Windows") ? "eu.medsea.mimeutil.detector.WindowsRegistryMimeDetector"
              : "eu.medsea.mimeutil.detector.OpendesktopMimeDetector");

        Collection<?> mimeTypes = null;
        try {
            mimeTypes = MimeUtil.getMimeTypes(File.getBytes());
            if(mimeTypes.equals("application/vnd.ms-excel") || mimeTypes.equals("application/json") 
                    || mimeTypes.equals("application/octet-stream"))
            {
                System.out.println("File typ is csv or json");
                mimeType = "success";
            }else{
                mimeType = "fail";
            }
        } catch (MimeException e1) {
            System.out.println(e1.getMessage());
            mimeType = "fail";
        } catch (IOException e1) {
            System.out.println(e1.getMessage());
            mimeType = "fail";
        }
}

Your issue is that MIME type checks in java are based on file extension. 您的问题是Java中的MIME类型检查基于文件扩展名。

In order to run actual file analysis try Apache Tika Mime Magic Detection . 为了运行实际的文件分析,请尝试使用Apache Tika Mime Magic Detection

Also, you can try one of the following: 此外,您可以尝试以下方法之一:

  1. ZIP the file before upload, then unzip on the server and test mime type 上传之前先压缩文件,然后在服务器上解压缩并测试mime类型
  2. Upload through scalable 3rd party solution eg S3 bucket 通过可扩展的第三方解决方案(例如S3存储桶)上传
  3. Rename the uploaded file but send the file name in a header or URL parameter and test that for mime type 重命名上载的文件,但在标头或URL参数中发送文件名,并测试其MIME类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM