我已经编写了一个简单的Spring + Angular应用程序,仅仅是为了了解它。 我有一个映射到URL的spring控制器,当请求到来时它会返回一个图像。
我已经编写了所有代码,弹簧控制器会将图像返回给我,但是当我在HTML中设置它时,它无法正确显示
这是我的弹簧控制器
@RequestMapping(value = "image/", method = RequestMethod.GET)
public ResponseEntity<byte[]> getChequeImage(HttpSessionsession,@PathVariable("itemId") Integer itemId,
HttpServletResponse response) {
try{
InputStream in = new FileInputStream(new File("path_to_image.jpg"));
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
return new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.OK);
}catch (IOException e){
LOGGER.error(e);
e.getMessage(), response);
return null;
}
}
这是我的HTML代码
<img src="{{image}}"/>
image是一个Angular变量。 Angular服务正在发送请求并将数据绑定到图像变量
这里是角度代码
@scope.image = "data:image/jpg," + data_from_the_api;
答案 0 :(得分:0)
您不能直接在页面上使用原始图像字节,但您可以进行Base64编码,这将是适应性的
@RequestMapping(value = "image/", method = RequestMethod.GET)
public ResponseEntity<String> getChequeImage(HttpSessionsession,@PathVariable("itemId") Integer itemId,
HttpServletResponse response) {
try{
InputStream in = new FileInputStream(new File("path_to_image.jpg"));
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
byte[] binaryData = IOUtils.toByteArray(in)
byte[] encodeBase64 = Base64.encodeBase64(binaryData);
String base64Encoded = new String(encodeBase64, "UTF-8");
return new ResponseEntity<String>(base64Encoded , headers, HttpStatus.OK);
}catch (IOException e){
LOGGER.error(e);
e.getMessage(), response);
return null;
}
}
正如TechMa9iac在评论中所说,你应该设置@scope.image = "data:image/jpg;base64," + data_from_the_api;