弹簧MVC显示Base64作为图像



我正在使用CKEditorWYSWIG作为我网站上的文本编辑器。 当用户将图像粘贴到编辑器上时,它将作为<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.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(...)

而文件来自filebucket3773303773410030Exif0000II*001000000000000000000000003773540021Ducky00010004000000A000037734103ohttp://ns.adobe.com/xap/1.0/00<?xpacket begin="357273277" id="W5M0MpCehiHzreSzNTczkc9d"?> (...)

谁能给我一个提示如何让它工作?

看起来这是一个愚蠢的错误。

我的数据库列contenttext类型,所以我byte[]存储为文本,所以浏览器没有正确解码文件并不奇怪。

将数据库列类型更改为bytea解决了问题。

最新更新