请教一下, SpringBoot 中使用 ResponseEntity 返回图片在游览器显示成字节流的问题。

2018-08-10 11:57:45 +08:00
 ukipoi

使用 ResourceLoader 获取文件,请问我要怎么做才能让游览器直接显示成图片呢?

private final ResourceLoader resourceLoader;

@RequestMapping(method = RequestMethod.GET, value = "/{filename:.+}")
    @ResponseBody
    public ResponseEntity<?> getFile(@PathVariable String filename) {

        try {
            return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(ROOT, filename).toString()));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
12751 次点击
所在节点    问与答
7 条回复
CFO
2018-08-10 12:07:52 +08:00
给流前端不太好处理吧 我的做法是存在文件服务器里给路径 小图直接 base64 给过去也行
kamil
2018-08-10 12:21:56 +08:00
RequestMapping 里的 produce 可以设置返回的 Content-Type 比如,image/jpg
把 ResponseEntity.ok 里的 toString 去掉,直接返回
elgae
2018-08-10 12:40:31 +08:00
用 StreamingResponseBody 比较合适
limuyan44
2018-08-10 12:59:12 +08:00
手动把 reponse 的 contenttype 设为 octet-stream 就可以了。
ukipoi
2018-08-10 13:05:42 +08:00
@limuyan44
谢谢,可以了
zjp
2018-08-10 13:47:12 +08:00
没运行代码,难道不是 2 楼才是正解吗
ukipoi
2018-08-10 15:16:16 +08:00
@zjp
是的,我看了返回的请求头。“ contenttype 设为 octet-stream ”在实际过程中就是“ image/png ”

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/478554

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX