V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
ukipoi
V2EX  ›  问与答

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

  •  
  •   ukipoi · 2018-08-10 11:57:45 +08:00 · 12718 次点击
    这是一个创建于 2085 天前的主题,其中的信息可能已经有所发展或是发生改变。

    使用 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();
            }
        }
    
    CFO
        1
    CFO  
       2018-08-10 12:07:52 +08:00 via Android
    给流前端不太好处理吧 我的做法是存在文件服务器里给路径 小图直接 base64 给过去也行
    kamil
        2
    kamil  
       2018-08-10 12:21:56 +08:00 via iPhone   ❤️ 1
    RequestMapping 里的 produce 可以设置返回的 Content-Type 比如,image/jpg
    把 ResponseEntity.ok 里的 toString 去掉,直接返回
    elgae
        3
    elgae  
       2018-08-10 12:40:31 +08:00
    用 StreamingResponseBody 比较合适
    limuyan44
        4
    limuyan44  
       2018-08-10 12:59:12 +08:00 via Android   ❤️ 1
    手动把 reponse 的 contenttype 设为 octet-stream 就可以了。
    ukipoi
        5
    ukipoi  
    OP
       2018-08-10 13:05:42 +08:00
    @limuyan44
    谢谢,可以了
    zjp
        6
    zjp  
       2018-08-10 13:47:12 +08:00 via Android
    没运行代码,难道不是 2 楼才是正解吗
    ukipoi
        7
    ukipoi  
    OP
       2018-08-10 15:16:16 +08:00
    @zjp
    是的,我看了返回的请求头。“ contenttype 设为 octet-stream ”在实际过程中就是“ image/png ”
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3234 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:22 · PVG 22:22 · LAX 07:22 · JFK 10:22
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.