我正在尝试根据请求将图像发送到前端,如果我将它作为JSON部分放入请求体中,它会起作用,但我想使用image / 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());
}
我缺少什么?
答案 0 :(得分:0)
尝试在servlet-context.xml文件中添加mvc注释,该文件注册ByteArrayHttpMessageConverter
<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>
答案 1 :(得分: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);
}