【问题标题】:IE image not getting loaded with X-Content-Type-Options:nosniffIE 图像未加载 X-Content-Type-Options:nosniff
【发布时间】:2015-10-09 17:00:49
【问题描述】:

简介

我有 spring MVC 应用程序,我正在从控制器加载图像。为了安全起见,我在我的 Spring 应用程序中添加了X-Content-Type-Options:nosniff

通过在springConfig xml中设置如下<security:content-type-options/>

问题:在这个 IE 没有加载控制器响应的图像之后。我怀疑响应中未设置内容类型。因为另一个响应 X-Content-Type-Options:nosniffContent-Type:image/png; 的站点工作正常。

试一试 我试图更改我的控制器以设置内容类型。但它没有发生。

@RequestMapping(value = "/getUserImage" , produces = org.springframework.http.MediaType.IMAGE_PNG_VALUE)
public @ResponseBody
void getUserImage(
        @RequestParam(value = "userId", required = false) int userId,
        HttpServletRequest request, HttpServletResponse response) {

    try {
        //Get file and add it to response
        IOUtils.copy(inputStream, response.getOutputStream());
        response.getOutputStream().flush();
        response.setContentType(org.springframework.http.MediaType.IMAGE_PNG_VALUE);
        response.setHeader("Content-Type","image/png");
        response.flushBuffer();
        inputStream.close();
    } catch (Exception e){
    }
}

TRY2 我尝试在方法拦截器中以相同的方式添加响应头,但仍然没有运气。

但在 Chrome 和 Firefox 中同样适用。

【问题讨论】:

    标签: spring internet-explorer


    【解决方案1】:

    试试这个:

     @RequestMapping(value = "/image/{personId}")
        @ResponseBody
        public HttpEntity<byte[]> getPhoto(@PathVariable int personId) {
            Person person = this.personService.getPersonById(personId);
            if (person != null && person.getProfileThumbnail() != null) {
                try {
                    byte[] image;
                    try {
                        image = org.apache.commons.io.FileUtils.readFileToByteArray(new File(msg + "/" + person.getUsername() + "/" + personId + ".png"));
                    } catch (FileNotFoundException e) {
                        image = org.apache.commons.io.FileUtils.readFileToByteArray(new File(defaultProfilePath));
                    }
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.IMAGE_PNG);
                    headers.setContentLength(image.length);
                    return new HttpEntity<>(image, headers);
                } catch (IOException ignored) {
                }
    
            } 
    }
    

    我基本上做的是检查文件系统上是否有用户的图像,如果没有,那么我正在加载默认图像。现在它适用于所有浏览器,所以即使 personid 为 0,我也会得到默认图像,还有其他原因,我没有在这里发布。

    【讨论】:

    • Content-type 已设置,但 IE 仍未加载图像。谁建立了这个 IE?世界上最受挫的网络浏览器。
    • 您返回 void,您希望它如何工作?或者这是你的拖钓尝试?
    • 没有博格,让我说清楚。它在 Chrome 和 FF 中工作。没有内容类型。我尝试添加您的代码,您的代码正在设置内容类型,但 IE 仍然没有加载图像,但 Chrome 和 FF 正在加载。
    • 更改您的返回类型。
    • 先生,正如您所说,我改变了。我说,我试过你的代码。它工作得很好,即设置内容类型,但 IE 没有加载图像。如何在不更改返回类型的情况下使用您的代码。它会抛出编译错误。
    猜你喜欢
    • 2017-01-08
    • 2019-07-11
    • 1970-01-01
    • 2017-04-04
    • 2013-04-05
    • 1970-01-01
    • 2014-03-09
    • 1970-01-01
    • 2014-03-17
    相关资源
    最近更新 更多