V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
ukipoi
V2EX  ›  问与答

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

  •  
  •   ukipoi · Aug 10, 2018 · 13301 views
    This topic created in 2818 days ago, the information mentioned may be changed or developed.

    使用 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  
       Aug 10, 2018 via Android
    给流前端不太好处理吧 我的做法是存在文件服务器里给路径 小图直接 base64 给过去也行
    kamil
        2
    kamil  
       Aug 10, 2018 via iPhone   ❤️ 1
    RequestMapping 里的 produce 可以设置返回的 Content-Type 比如,image/jpg
    把 ResponseEntity.ok 里的 toString 去掉,直接返回
    elgae
        3
    elgae  
       Aug 10, 2018
    用 StreamingResponseBody 比较合适
    limuyan44
        4
    limuyan44  
       Aug 10, 2018 via Android   ❤️ 1
    手动把 reponse 的 contenttype 设为 octet-stream 就可以了。
    ukipoi
        5
    ukipoi  
    OP
       Aug 10, 2018
    @limuyan44
    谢谢,可以了
    zjp
        6
    zjp  
       Aug 10, 2018 via Android
    没运行代码,难道不是 2 楼才是正解吗
    ukipoi
        7
    ukipoi  
    OP
       Aug 10, 2018
    @zjp
    是的,我看了返回的请求头。“ contenttype 设为 octet-stream ”在实际过程中就是“ image/png ”
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4439 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 00:11 · PVG 08:11 · LAX 17:11 · JFK 20:11
    ♥ Do have faith in what you're doing.