【问题标题】:Could not set ContentType in Spring HttpServletResponse in Spring无法在 Spring 中的 Spring HttpServletResponse 中设置 ContentType
【发布时间】:2017-11-26 10:35:38
【问题描述】:

我实现了一个 REST API,如下所示。浏览器 - 作为客户端 - 无法执行我从提到的 REST 给出的 javascript 并打印错误,例如 Refused to execute script from 'http://localhost:8083/vendor.js' because its MIME type ('') is not executable, and strict MIME type checking is enabled。这意味着当我为响应设置内容类型时,没有为响应设置 MIME 类型,但它被应用了。

@RequestMapping(value = "/{resoucePath:.+}", method = RequestMethod.GET)
public void getResouce(@PathVariable String resoucePath, HttpServletResponse response) {
    String myPath = ...; // I set resource path here
    File resouce = new File(myPath);
    try {
        InputStream is = new FileInputStream(resouce);
        IOUtils.copy(is, response.getOutputStream());
        response.setContentType(mimeTypesMap.getContentType(resouce));
        response.flushBuffer();
    } catch (IOException ex) {
        // log error
        throw new RuntimeException("IOError writing file to output stream", ex);
    }
}

我的错误是什么?为什么没有在响应中设置 content-type?

【问题讨论】:

标签: javascript java spring rest


【解决方案1】:

我发现了问题。不应用内容类型,因为它是在写入响应后设置的。我重新排序以下行并解决了问题:

有问题的代码:

IOUtils.copy(is, response.getOutputStream());
response.setContentType(mimeTypesMap.getContentType(resouce));

解决的代码:

response.setContentType(mimeTypesMap.getContentType(resouce));
IOUtils.copy(is, response.getOutputStream());

【讨论】:

    猜你喜欢
    • 2018-04-05
    • 2017-02-19
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 2016-12-26
    • 2020-06-18
    • 2019-11-12
    相关资源
    最近更新 更多