首页 > 解决方案 > 字节[]到图像转换弹簧启动

问题描述

我需要在spring boot中使用byte []来进行图像转换,根据以下代码我可以获得图像,但是它无法显示。所以我需要在调用 API 时显示图像的解决方案,http://localhost:9000/files/d317447b-7235-47c5-9923-bc65aae89d76

@GetMapping("/files/{id}")
    public ResponseEntity<byte[]> getFile(@PathVariable String id) {
        FileDB fileDB = storageService.getFile(id);
        log.info("{}->{}","FILES_GET_BY_ID:",id);
        return ResponseEntity.ok()
                .header(HttpHeaders.ACCEPT, "attachment; filename=\"" + fileDB.getName() + "\"")
                .body(fileDB.getData());
    }

最后我得到了解决方案。

@GetMapping("/files/{id}")
    public ResponseEntity<byte[]> getFile(@PathVariable String id) {
        FileDB fileDB = storageService.getFile(id);
        log.info("{}->{}","FILES_GET_BY_ID:",id);
        return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_JPEG)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileDB.getName() + "\"")
                .body(fileDB.getData());
    }

标签: javaspring-bootstream

解决方案


我认为您需要更改 HTTP 标头而不是使用 ACCEPT 使用标头 Content-Disposition 还将响应类型设置为相关类型。


推荐阅读