Spring Boot 根据文件扩展名获取 contentType 的方式,如下代码所示:

    String filename = "hello.png";
    Optional<MediaType> mediaType = MediaTypeFactory.getMediaType(filename);
    mediaType.ifPresent(type -> response.setContentType(type.toString()));

以上代码根据文件名(可以是文件名,也可以只是扩展名 .png)获取了 contentType,如果获取到结果则设置到 response 的 header 中。

其中所有 mime-type 的库源自 spring 内置文件 spring-web-5.x.x.jar!\org\springframework\http\mime.types


(END)