无法在Spring中的Spring HttpServletResponse中设置ContentType

时间:2017-06-23 00:47:43

标签: javascript java spring rest

我实现了一个REST API,如下所示。浏览器 - 作为客户端 - 无法执行我提到的REST提供的javascripts并打印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);
    }
}

我的错误是什么?为什么没有设置内容类型作为响应?

1 个答案:

答案 0 :(得分:0)

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

有问题的代码:

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

已解决的代码:

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