SpringBoot下图片展示方式

本文介绍两种从byte[]格式数据展示图片的方法:一是转换为Base64字符串并在HTML<img>标签中展示;二是直接通过response输出byte[]数据。文章提供了具体的Java代码示例,包括使用FastDFSClient下载文件并处理的完整流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   第一种 将图片byte[]转换成Base64字符串,在<img> src中展示。

 服务端代码示例

@Slf4j
@Controller
@EnableWebMvc
public class ImgViewController {

@RequestMapping(value = "/imgShow", method = RequestMethod.GET)
public String imgShow(String imgPath, Model model) {
try {
FastDFSClient fdfsClient = new FastDFSClient();
byte[] bytes = fdfsClient.downloadFile(imgPath);
String imgStr = Base64.encodeBase64String(bytes);
String imgData = new StringBuffer("data:image/jpg;base64,").append(imgStr).toString();
model.addAttribute("imgData", imgData);
return "imgShow";
} catch (Exception e) {
log.error("获取图片异常!{}", e);
return "fail";
}
}
}
页面示例
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<div>
<img src= "${imgData}"/>
</div>
</body>
</html>

第二种 将图片byte[]直接扔给response.
服务端代码示例
@Slf4j
@RestController
public class ImgViewController {

@RequestMapping(value = "/imgShow", method = RequestMethod.GET)
public void imgShow(String imgPath, HttpServletResponse response) {
try {
ServletOutputStream out = response.getOutputStream();
       FastDFSClient fdfsClient = new FastDfSClient();
       byte[] bytes = fdfsClient.downloadFile(imgPath);
       out.write(bytes);
       out.flush();
       out.close();
} catch (Exception e) {
log.error("获取图片异常!{}", e);
}
}
}

 

转载于:https://www.cnblogs.com/Jode-blog/p/10341966.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值