将 byte[] 转换为图像并在 jsp 上显示 [英] Convert byte[] to image and display on jsp
问题描述
我正在尝试在 jsp 页面上显示上传的图片(现在是字节数组).现在,byte[] 列存在于数据库中,必须转换为图像.
I'm trying to display an uploaded picture (which is now a byte array) on a jsp page. Now, the byte[] column exists in the database and has to be converted to an image.
这是我一直在尝试的:
jsp页面部分表格:
<c:forEach var="user" items="${userList}">
<tr>
<td>${user.fileName}</td>
<td>
<img src="data:image/jpg;base64,${user.imageFile}" alt="No image">
</td>
从 MultipartFile 对象中获取字节数组的控制器的一部分:
Part of the controller that takes an array of bytes from a MultipartFile object:
@RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView userRegister(@ModelAttribute("user") @Valid User user, BindingResult result, ModelMap model, @RequestParam("fileData") MultipartFile fileData) throws Exception {
if (!fileData.isEmpty() && fileData != null) {
byte[] bytes = fileData.getBytes();
user.setFileName(fileData.getOriginalFilename());
user.setImageFile(bytes);
}
}
如果需要任何其他信息,请告诉我.谢谢.
If any additional information is needed, please let me know. Thanks.
推荐答案
您可以向您的 User
添加瞬态 base64imageFile
属性.它将保存图像的 base64 编码字符串,您可以像在 jsp 中访问它
You can add a tranisent base64imageFile
property to your User
. It will hold the base64 encoded string of the image, which you can access in your jsp like
<img alt="img" src="data:image/jpeg;base64,${user.base64imageFile}"/>
在你的方法中你应该进行编码,比如
And in your method you should do the encoding, somethig like
@RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView userRegister(@ModelAttribute("user") @Valid User user, BindingResult result, ModelMap model, @RequestParam("fileData") MultipartFile fileData) throws Exception {
if (!fileData.isEmpty() && fileData != null) {
byte[] bytes = fileData.getBytes();
user.setFileName(fileData.getOriginalFilename());
user.setImageFile(bytes);
byte[] encodeBase64 = Base64.encodeBase64(bytes);
String base64Encoded = new String(encodeBase64, "UTF-8");
user.setBase64image(base64encoded);
}
}
IOUtils
和 Base64
是来自 org.apache.commons
的一个方便的 util 类,查找应该没有问题
IOUtils
and Base64
are a handy util classes from org.apache.commons
, shouldn't have a problem finding
这篇关于将 byte[] 转换为图像并在 jsp 上显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!