我正在使用CKEditorWYSWIG
作为我的网站上的文本编辑器。 当用户粘贴到编辑的图像是在后期被作为<img src="data:image/png;base64,iVBORw0KGgoAAAANsd..." />
spring mvc display base64 as image
我想获得这个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(...)
而文件从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"?> (...)
谁能给我一个提示如何使它起作用?
你可以在响应中编写你的文件,如http://www.codejava.net/frameworks/spring/spring-mvc-sample-application-for-downloading-files所述,或者返回HttpEntity,如http:/ /memorynotfound.com/spring-mvc-download-file-examples/ – StanislavL