您可以将HTML图像标记的src属性设置为控制器方法吗? [英] Can you set the src attribute of an HTML image tag to a controller method?

查看:151
本文介绍了您可以将HTML图像标记的src属性设置为控制器方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道你可以这样做

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

但如果我的控制器方法用 @ResponseBody

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的<$ c $实际设置 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).

这篇关于您可以将HTML图像标记的src属性设置为控制器方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆