2018-11-15 · Develop

Swagger API 中无法正常显示图片

随着互联网技术的发展,现在的网站架构基本都由原来的后端渲染,变成了:前端渲染、先后端分离的形态,而且前端技术和后端技术在各自的道路上越走越远。

前端和后端的唯一联系,变成了API接口;API文档变成了前后端开发人员联系的纽带,变得越来越重要,swagger就是一款让你更好的书写API文档的框架。

在 SpringBoot 集成 Swagger 的时候,出现无法显现验证码图片的问题,请求后,一致处于加载状态下,通过 F12 debug 发现,图片已经返回给了 Swagger-ui 但是没有正常的显示。并且 JS 曝出如下错误。

swagger-ui.min.js:14 Uncaught TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.
    at C.n.showStatus (swagger-ui.min.js:14)
    at showCompleteStatus (swagger-ui.min.js:14)
    at response (swagger-ui.min.js:9)
    at h (swagger-ui.min.js:7)
    at t.on.response (swagger-ui.min.js:7)
    at swagger-ui.min.js:7
    at h.callback (swagger-ui.min.js:13)
    at h.<anonymous> (swagger-ui.min.js:13)
    at h.r.emit (swagger-ui.min.js:13)
    at XMLHttpRequest.n.onreadystatechange (swagger-ui.min.js:13)

先说说环境

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.7.0</version>
</dependency>

看看后端的代码

@GetMapping(value = "captcha.jpg")
@ApiOperation("获取验证码")
public void captcha(HttpServletResponse response, String uuid) throws ServletException, IOException {
    response.setHeader("Cache-Control", "no-store, no-cache");
    response.setContentType("image/jpeg");
    //获取图片验证码
    BufferedImage image = sysCaptchaService.getCaptcha(uuid);

    ServletOutputStream out = response.getOutputStream();
    ImageIO.write(image, "jpg", out);
    IOUtils.closeQuietly(out);
}

其实原因很简单,没有正确的设置响应头。解决如下

@GetMapping(value = "captcha.jpg", produces = MediaType.IMAGE_JPEG_VALUE)
@ApiOperation("获取验证码")
public void captcha(HttpServletResponse response, String uuid) throws ServletException, IOException {
    ...
}

或者

@GetMapping(value = "captcha.jpg")
@ApiOperation(value = "获取验证码", produces = MediaType.IMAGE_JPEG_VALUE)
public void captcha(HttpServletResponse response, String uuid) throws ServletException, IOException {
    ...
}