Spring MVC (Boot) does not send MIME type for certain files (WOFF, etc)

岁酱吖の 提交于 2019-11-29 04:35:09

问题


I am writing a spring boot based application and noticed a few warnings in chrome. It complains that for example web fonts (extension woff) are send as plain/text instead of their correct mime type.

I am using the regular mechanism for static files without special configuration. The sourcecode I found looks like it's not possible to add more mimetypes for the "stock" ResourceHandler. The Resourcehandler dispatches the mime type recognition to the servlet container, which is the default tomcat for spring-boot 1.2.

Am I missing something? Does someone know an easy way to to enhance the resource mapping to serve more file types with the correct mime type?

Right now I'm thinking to write a filter that is triggered for static content and patches missing mimetypes after the fact. Maybe I should create a feature request at springsource... ;-)


回答1:


OK, found it myself :-)

In Spring boot you can customize the servlet container with this customizer and add new mimetypes there.

(UPDATE)

Spring-boot 2.x:

@Component
public class ServletCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
        mappings.add("woff", "application/x-font-woff");
        factory.setMimeMappings(mappings);
    }
}

Spring-boot 1.x:

@Component
public class ServletCustomizer implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
        mappings.add("woff","application/font-woff");
        mappings.add("woff2","application/font-woff2");
        container.setMimeMappings(mappings);
    }
}


来源:https://stackoverflow.com/questions/27617275/spring-mvc-boot-does-not-send-mime-type-for-certain-files-woff-etc

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