什么时候浏览器将application/octet-stream作为Content-Type发送?

gue*_*rda 9 jsf content-type file-upload request-headers

我正在使用JSF开发文件上传.该应用程序保存有关该文件的三个日期:

  • 文件名
  • 字节
  • 内容类型由浏览器提交.

我的问题是一些文件以内容类型=保存,application/octet-stream即使它们是*.doc文件oder *.pdf.

浏览器何时提交此类内容类型?
我想清理数据库,所以我需要知道浏览器信息何时不正确.

Bal*_*usC 8

忽略浏览器发送的值.这确实取决于客户端平台,浏览器和使用的配置.

如果您希望基于文件扩展名完全控制内容类型,则可以使用自己更好地确定内容类型ServletContext#getMimeType().

String mimeType = servletContext.getMimeType(filename);
Run Code Online (Sandbox Code Playgroud)

默认的mime类型在相关web.xml的servletcontainer中定义.例如Tomcat,它位于/conf/web.xml.您可以在webapp中扩展/覆盖它,/WEB-INF/web.xml如下所示:

<mime-mapping>
    <extension>xlsx</extension>
    <mime-type>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</mime-type>
</mime-mapping>
Run Code Online (Sandbox Code Playgroud)

您还可以根据实际文件内容确定mime类型(因为文件扩展名本身可能不准确,可能被客户端欺骗),但这是很多工作.考虑使用第三方库来完成所有工作.我发现JMimeMagic对此很有用.您可以按如下方式使用它:

String mimeType = Magic.getMagicMatch(file, false).getMimeType();
Run Code Online (Sandbox Code Playgroud)

请注意,它不支持所有 mimetypes可靠.您也可以考虑两种方法的组合.例如,如果一个返回null或application/octet-stream使用另一个.或者,如果两者都返回不同但"有效"的mimetype,则更喜欢JMimeMagic返回的mimetype.

哦,我几乎忘了添加,在JSF中你可以获得ServletContext如下:

ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
Run Code Online (Sandbox Code Playgroud)

或者,如果您恰好使用JSF 2.x,请ExternalContext#getMimeType()改用.