[英]spring mvc display base64 as image
我在网站上使用CKEditor WYSWIG
作为文本编辑器。 当用户将图像粘贴到编辑器上时,它以<img src="data:image/png;base64,iVBORw0KGgoAAAANsd..." />
我想获取此base64
字符串,将其保存在数据库中,然后创建类似/image/{id}
端点,该端点将显示此图像,因此在发布时,我不必将整个base64
字符串放在图像源中,而只需将URL放在上面所示的位置。
这就是我将base64
保存为byte[]
:
@RequestMapping(value = {"/main/createpost"}, method = RequestMethod.POST)
public String postPost(Model model, Principal principal,@RequestParam(name="editor-content") String postPayload) throws IOException {
postPayload = checkAndSavePhotos(postPayload);
model.addAttribute("editor",postPayload);
return "createpost";
}
checkAndSavePhotos
正在检查编辑器是否包含任何图像,如果包含,则将其存储在数据库中:
private String checkAndSavePhotos(String postPayload) throws IOException {
int i =1;
Pattern pattern = Pattern.compile(".*<img src=\".*;base64,(.*?)\".*/>");
Matcher matcher = pattern.matcher(postPayload);
while (matcher.find()) {
PostPhoto postPhoto = new PostPhoto();
byte[] bytes = Base64.getDecoder().decode(matcher.group(i).getBytes());
MultipartFile mf =null;
try {
BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(bytes));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(originalImage, "png", baos);
baos.flush();
mf = new MockMultipartFile("test", baos.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
postPhoto.setContent(mf.getBytes());
postPhoto = postPhotoService.save(postPhoto);
}
return null;
}
我这样做是因为在我使用FileBucket
另一种带有<input type='file' />
FileBucket
,足以显示fileBucket.getFile().getBytes();
为了显示图像。 我试图从byte[]
创建MultipartFile
并以相同的方式进行操作。
我要显示图像的端点:
@RequestMapping(value = "/main/postphoto/{imageId}")
@ResponseBody
public byte[] getImage(@PathVariable Long imageId) throws IOException {
PostPhoto image = postPhotoService.findById(imageId);
return image.getContent();
}
现在,当我查看数据库content
列时看起来像: \\x89504e470d0a1a0a0000000d49484452000000280000002808060000008cfeb86d0000033f4944415478daed9(...)
而文件filebucket
文件\\377\\330\\377\\341\\000\\030Exif\\000\\000II*\\000\\010\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\377\\354\\000\\021Ducky\\000\\001\\000\\004\\000\\000\\000A\\000\\000\\377\\341\\003ohttp://ns.adobe.com/xap/1.0/\\000<?xpacket begin="\\357\\273\\277" id="W5M0MpCehiHzreSzNTczkc9d"?> (...)
谁能给我一个提示,使其如何工作?
看来这是一个愚蠢的错误。
我的数据库列content
是text
类型,因此我将byte[]
存储为文本,因此浏览器未正确解码该文件并不为过。
将数据库列类型更改为bytea
可解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.