【问题标题】:Spring Controller sending image to client results in 406Spring Controller 向客户端发送图像导致 406
【发布时间】:2015-07-06 16:10:27
【问题描述】:

我正在尝试根据请求将图像发送到前端,如果我将其作为 JSON 的一部分放入请求正文中,它可以工作,但我想使用图像/png,更有意义,但我得到 406当我尝试时。

控制器:

@RequestMapping(value = RESTPaths.EQUIPMENT_FILE_GET_IMAGE + "/{equipmentId}", method = RequestMethod.GET,
        produces = MediaType.IMAGE_PNG_VALUE)
public @ResponseBody byte[] insertDataFile(@PathVariable("equipmentId") final Long equipmentId)
        throws InternalServerError {
    return equipmentFileService.getImage(equipmentId);
}

测试(客户端):

mockMvc.perform(
            get(RESTPaths.EQUIPMENT_FILE_CONTROLLER + RESTPaths.EQUIPMENT_FILE_GET_IMAGE + "/" + equipment.getId())
                    .with(httpBasic("user", "password")).accept(MediaType.IMAGE_PNG)
                    .contentType(TestUtil.APPLICATION_JSON_UTF8)).andDo(MockMvcResultHandlers.print()).andExpect(status().isOk());
}

我错过了什么?

【问题讨论】:

  • 您能否说明您使用的是哪个版本的 Spring,这适用于 4.1 +

标签: spring image bytearray http-status-code-406


【解决方案1】:

尝试在注册 ByteArrayHttpMessageConverter 的 servlet-context.xml 文件中添加 mvc 注释

<mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>image/jpeg</value> <value>image/png</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>

【讨论】:

  • 建议的解决方案是否解决了您的问题或者仍然无法正常工作
  • 我试过了(使用 java 配置),没有帮助,我正在查看我的版本
【解决方案2】:

已解决:

@RequestMapping(value = RESTPaths.EQUIPMENT_FILE_GET_IMAGE + "/{equipmentId}", method = RequestMethod.GET)
@ResponseBody
public  ResponseEntity<byte[]> getImage(@PathVariable("equipmentId") final Long equipmentId)
        throws InternalServerError {
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_JPEG);
    return new ResponseEntity<byte[]>(equipmentFileService.getImage(equipmentId), headers, HttpStatus.OK);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多