【问题标题】:Spring Boot: Serving image from file - containing it base64 encodedSpring Boot:从文件中提供图像 - 包含 base64 编码
【发布时间】:2017-03-13 16:51:12
【问题描述】:

我有 base64 编码的图像(例如 gif)。我想通过 Spring-Boot web 为它们提供服务,而无需在服务器端对它们进行 base64 解码。客户端应该进行 base64 解码。很明显,浏览器可以做到这一点。看一下https://jsfiddle.net/casiano/xadvz/。使用内联在 img-tag 的 src 中的 base64 编码图像,它可以正常工作。现在假设我在服务器上的文件中有来自该示例的 base64 编码图像(myfile_gif.txt,内容为“R0lG ... hAAOw==”)。

我想通过 Spring-Boot Web 提供该文件 myfile_gif.txt,而不在服务器端将 base64 解码为二进制文件。它应该以某种方式工作,以便以下 html sn-p 实际显示图像

<img src="http://localhost:8080/rest/testimage" />

目前我有以下

@RestController
@RequestMapping("/rest")
public class RestController {
    @RequestMapping(path = "/testimage", method = RequestMethod.GET)
    @ResponseBody
    public HttpEntity<?> getTestImage() {
        InputStream stream = null;
        try {
            stream = new FileInputStream(new File("myfile_gif.txt"));
        } catch (FileNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }

        if (stream != null) {
            return ResponseEntity.ok()
            .contentType(MediaType.parseMediaType("image/gif;base64"))
            .header(HttpHeaders.CONTENT_ENCODING, "base64")
            .header(HttpHeaders.TRANSFER_ENCODING, "base64")
            .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"my.gif\"")
            .body(new InputStreamResource(stream));
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
    }
}

但它不起作用 - 图像没有显示在浏览器中。我可以在浏览器的开发人员控制台中看到对http://localhost:8080/rest/testimage 的请求得到响应代码200,它说传输了2,54kb,所以它似乎可以正常服务。选定的响应标头

  • 内容编码:base64
  • 传输编码:base64,分块
  • 内容类型:image/gif;charset=UTF-8

它尝试了各种我能想到的东西,但无法让它发挥作用。你能帮我完成它吗?

【问题讨论】:

标签: html image encoding spring-boot base64


【解决方案1】:

选项 1:

String base64 = "your file"; // get base-64 encoded string
    byte[] bytes = Base64.decodeBase64(base64);
    try (InputStream inputStream = new ByteArrayInputStream(bytes)) {
        StreamUtils.copy(inputStream, response.getOutputStream());
        response.setContentType(MediaType.IMAGE_PNG_VALUE);
    } catch (IOException e) {
        // handle
    }
    return new ResponseEntity(HttpStatus.OK);

选项 2:

@RequestMapping("/image/{id}")
@ResponseBody
public HttpEntity<byte[]> getImage(@PathVariable String id) {

   // 1. download img your location... 
    byte[] image = ... 

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_JPEG);
    headers.setContentLength(image.length);

    return new HttpEntity<byte[]>(image, headers);
}

【讨论】:

  • 选项 1 将在服务器端进行解码。我想将编码的字符串发送到浏览器(并且可以这样做)并让它(浏览器)对其进行解码。选项 2 我不明白。
  • 选项 1 中的 response 是什么?
  • 响应是 OPTION 1 是 HttpServletResponse 实例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-01
  • 1970-01-01
  • 2011-04-12
  • 2012-04-16
  • 1970-01-01
相关资源
最近更新 更多