SpringBoot下图片展示方式

   第一种 将图片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);
}
}
}

 

posted on 2019-01-31 14:51  旧梦*  阅读(698)  评论(0编辑  收藏  举报

导航