Thymeleaf从数据库加载图片到页面失败,请求排查原因
数据库图片无法在浏览器正常显示的问题排查与修复
我搞不懂怎么把服务器数据库里的图片传到浏览器,现在代码跑起来有问题。从数据库读字节存到磁盘里图片能正常打开,但浏览器里显示异常。
HTML代码片段
<div th:fragment="image_list"> image will be here <p> <img class="picture" th:src="@{/image/1}"/> </div>
Java控制器代码
@GetMapping(value = "/{id}") @ResponseBody public ResponseEntity<InputStreamResource> getCarImage(@PathVariable Long id) { var image = imageService.getOne(id); var imageDecompressed = decompressBytes(image.getImage()); InputStream inputStream = new ByteArrayInputStream(imageDecompressed); return ResponseEntity.ok() .contentLength(image.getImage().length) .contentType(MediaType.IMAGE_JPEG) .body(new InputStreamResource(inputStream)); } public static byte[] decompressBytes(byte[] data) { Inflater inflater = new Inflater(); inflater.setInput(data); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length); byte[] buffer = new byte[1024]; try { while (!inflater.finished()) { int count = inflater.inflate(buffer); outputStream.write(buffer, 0, count); } outputStream.close(); } catch (IOException ioe) { } catch (DataFormatException e) { } return outputStream.toByteArray(); }
问题截图

问题排查与修复
1. 修正Content-Length参数
当前代码用了压缩前的字节长度image.getImage().length,但实际返回给浏览器的是解压后的流,长度不匹配会导致浏览器解析图片失败。改成解压后的数组长度:
.contentLength(imageDecompressed.length)
2. 不要静默吞掉异常
decompressBytes方法里的空catch会掩盖解压错误,比如数据格式不对、解压失败等问题根本无法察觉。至少要打印日志或者抛出异常:
catch (IOException ioe) { ioe.printStackTrace(); throw new RuntimeException("图片解压失败", ioe); } catch (DataFormatException e) { e.printStackTrace(); throw new RuntimeException("图片数据格式错误", e); }
3. 优化资源类型(可选)
对于字节数组,用ByteArrayResource比InputStreamResource更简洁,不需要额外包装字节流:
return ResponseEntity.ok() .contentLength(imageDecompressed.length) .contentType(MediaType.IMAGE_JPEG) .body(new ByteArrayResource(imageDecompressed));
额外验证步骤
- 确认从数据库拿到的字节数据是有效的压缩格式
- 对比
decompressBytes输出的字节数组和存到磁盘的文件内容是否完全一致
内容的提问来源于stack exchange,提问作者TryHard
相关产品推荐
相关产品推荐

