您可以将HTML图像标记的src属性设置为控制器方法吗?
我知道你可以这样做
<img src="http://some_svg_on_the_web" />
但如果我的控制器方法用 @ResponseBody $注释怎么办? c $ c>
But what if I have a controller method annotated with @ResponseBody
@RequestMapping(value="getSVG")
public @ResponseBody String getSVG(HttpServletRequest request, HttpServerletResponse response) {
String SVG = // build the SVG XML as a string
return SVG;
}
我可以说
<img src="/getSVG" />
我已经测试过,控制器肯定被击中,但页面上没有显示图像。
I have tested and the controller is definitely being hit but no image is being shown on the page.
我认为问题是Spring将默认内容类型设置为 application / octet-stream
,浏览器无法读取您的XML。相反,您需要通过 HttpServerletResponse
或使用Spring的 Content-Type 标头。 c> ResponseEntity 。
I believe the problem is Spring is setting the default content type to application/octet-stream
and the browser can't read your XML as that. Instead, you need to actually set the Content-Type
header, either through the HttpServerletResponse
or with Spring's ResponseEntity
.
@RequestMapping(value="getSVG")
public @ResponseBody ResponseEntity<String> getSVG(HttpServletRequest request, HttpServerletResponse response) {
String SVG = // build the SVG XML as a string
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.valueOf("image/svg+xml"));
ResponseEntity<String> svgEntity = new ResponseEntity<String>(svg, headers, HttpStatus.OK);
return svgEntity;
}
您将XML作为的事实字符串
并不重要,您可以使用 getBytes()
来制作内容 byte []
。您还可以使用 Resource
类让Spring直接从类路径或文件系统资源中获取字节。你会相应地参数化 ResponseEntity
(有许多支持的类型)。
The fact that the you have the XML as a String
doesn't really matter, you could've used getBytes()
to make the content byte[]
. You can also use the Resource
class to have Spring get the bytes directly from a classpath or file system resource. You would parameterize ResponseEntity
accordingly (there are a number of supported types).