Can you set the src attribute of an HTML image tag

2019-06-01 02:39发布

I know that you can do this

<img src="http://some_svg_on_the_web" />

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;
}

Can I then say

<img src="/getSVG" />

I have tested and the controller is definitely being hit but no image is being shown on the page.

1条回答
▲ chillily
2楼-- · 2019-06-01 03:32

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;
}

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).

查看更多
登录 后发表回答