我有下一个问题 - 每张图片发送请求:
<img src="getImage/9.jpg"/>
Spring MVC Controller:
@Secured( "ROLE_ADMIN")
@RequestMapping(value = "/getImage/{img_name:.+}")
public byte[] getImage(@PathVariable String img_name) {
byte[] data;
try {
String realpath = "D:\\Project\\images\\" + img_name;
Path path = Paths.get(realpath);
data = Files.readAllBytes(path)
}catch (IOException e){
data = null;
}
return data;
}
在浏览器方面,我收到了下一个错误:
406 Not Acceptable
这种问题可能是什么原因?我应该从服务器端发送什么数据才能使<img src="getImage/9.jpg"?>
正常工作。
答案 0 :(得分:1)
请将此代码添加到spring-context.xml文件中,该文件注册了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
,班级应为
@Secured( "ROLE_ADMIN")
@RequestMapping(value = "/getImage/{img_name:.+}")
public ResponseEntity<byte[]> getImage(@PathVariable String img_name)
throws InternalServerError {
byte[] data;
try {
String realpath = "D:\\Project\\images\\" + img_name;
Path path = Paths.get(realpath);
data = Files.readAllBytes(path)
}catch (IOException e){
data = null;
}
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
return new ResponseEntity<byte[]>(data , headers, HttpStatus.OK);
}