【问题标题】:Getting null for the content type of png image为 png 图像的内容类型获取 null
【发布时间】:2013-10-21 06:47:10
【问题描述】:

当我尝试获取 png 图像的内容类型时,我得到了 null

以下是我尝试在servlet 中获取内容类型的方法:

String contentType = getServletContext().getMimeType(image.getName());

我收到contentType = nullimage.getName() 返回png 图像的名称。

我尝试了其他方式来获取相同png图像的内容类型:

String contentType = new MimetypesFileTypeMap().getContentType("imageName.png");

上面的代码给了我contentType = application/octet-stream

我的问题是为什么我会为同一张图片获得不同的内容类型,我应该怎么做才能获得正确的内容,即image/x-png for .png 类型的图片

【问题讨论】:

  • 我没有使用 jdk 7,所以 java.io.Files 选项对我来说很接近。
  • 你有没有为你的目的尝试过 apache FileUtils?
  • 没有。我为此使用 struts form bean。
  • 没关系,您为此使用了哪种数据类型?我建议使用 FormFile。
  • 是的,我正在使用相同的 FormFile。

标签: java jakarta-ee servlets struts


【解决方案1】:

我知道这可能为时已晚,但今天偶然发现了这一点。就我而言,问题是:

从应用服务器检索文件的 MIME 类型。大多数应用程序服务器,包括 IBM® WebSphere® Application Server 和 Tomcat,都带有一些预定义的 MIME 类型。但是,默认类型中仍然缺少许多常见的文件格式,必须由服务器管理员定义。

找到here

【讨论】:

    【解决方案2】:

    我的解决方案:

    String contentType = new MimetypesFileTypeMap().getContentType("imageName.PNG");
    //contentType = null
    
    String contentType = new MimetypesFileTypeMap().getContentType("imageName.png");
    //work for me
    

    【讨论】:

    • 感谢您的回答!可以通过添加您获得的内容类型来改进它,以及 Vishrant 如何确保他们的 image.getName() 函数返回的值是 getContentType 的有效输入。
    猜你喜欢
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 2022-01-11
    • 2020-06-16
    • 2023-04-08
    相关资源
    最近更新 更多