【发布时间】: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
它尝试了各种我能想到的东西,但无法让它发挥作用。你能帮我完成它吗?
【问题讨论】:
-
这里是 myfile_git.txt:gist.github.com/steff1193/…
标签: html image encoding spring-boot base64