首页 > 解决方案 > 无法让此控制器返回具有正确 mime 类型的文件

问题描述

我无法让以下简单的控制器与 Spring Framework 5.2 和 Springboot 2.2 与 Kotlin 1.3.50 一起正常工作。它是一个简单的 FileServerController,它为下面的文件提供服务 ~ 但我似乎得到了控制器的双重调用,并且即使我明确设置了返回文件的 mime 类型,它也始终是 application/json。如果我没有返回具有正确 mime 类型的 xml 文件,那么我无法让浏览器对其执行 XSL 转换。我有点确定(但不是肯定的)它的非 Kotlin 版本会起作用。有人可以建议我尝试其他的东西。非常感谢。

@Controller
class FileServerController {
    @RequestMapping(value = ["/**"])
    fun getFile(request: HttpServletRequest, response: HttpServletResponse): FileSystemResource {
        var fileName = request.servletPath
        val HOME = System.getenv("HOME")

        println("Requested ${fileName}")

        fileName = "${HOME}${fileName}"
        val file = File(fileName)

        if (file.canRead()) {
            println("Serving ${fileName}")
            if(fileName.endsWith(".xml")) {
                response.contentType = "text/xml"
            } else if(fileName.endsWith(".xslt")) {
                response.contentType = "application/xslt+xml"
            }
            return FileSystemResource(file)
        } else {
            println("Couldn't find ${fileName}")
            throw NotFoundException(fileName)
        }
    }
}

我的 pom.xml 中的依赖项是

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-reflect</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-stdlib-jdk8</artifactId>
        </dependency>

标签: spring-bootspring-mvckotlin

解决方案


推荐阅读