0

我正在尝试根据请求将图像发送到前端,如果我将它作为 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());
}

我错过了什么?

4

2 回答 2

0

尝试在注册 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>
于 2015-07-06T19:53:34.670 回答
0

解决了:

@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);
}
于 2015-07-10T11:30:13.923 回答