[英]upload and view image in spring mvc
我正在尝试在数据库中上传图像,然后在使用Spring MVC开发的Web应用程序中的jsp上显示该图像。 我已经阅读了与此问题有关的所有问题,但我没有理解。 我当时正在考虑将图像保存在一个blob字段中,而不是一个clob字段中。 这是个好主意吗?
我用文件输入创建了一个多部分表单。
<form:form method="POST" action="monorigineEdit" modelAttribute="formMonorigineEdit" enctype="multipart/form-data">
...
<input type="file" name="image">
...
</form:form>
在控制器中,我以这种方式正确获得了Multipartfile
public String monorigineEdit(@RequestParam("image") MultipartFile file, HttpServletRequest request, ModelMap model,
@ModelAttribute(value = "formMonorigineEdit") @Valid MonorigineDTO monorigineDTO, BindingResult result, RedirectAttributes redirectAttrs) throws FacadeException
我想出于测试目的,只是将图像转发到base64中的jsp并显示,以这种方式在控制器中
...
File auxFile = multipartToFile(file);
FileInputStream fi = new FileInputStream(auxFile);
byte[] byteArrayImage = Base64.encodeBase64(IOUtils.toByteArray(fi));
model.put("myImage", byteArrayImage);
return new String("monorigineEditTemplate");
并在jsp中使用此标签
<img id="myImg" name="myImg" src="data:image/jpeg;base64,<c:out value='${myImage}'/>" >
方法multipartToFile就是这样的:
public File multipartToFile(MultipartFile multipart) throws IllegalStateException, IOException
{
File convFile = new File(multipart.getOriginalFilename());
multipart.transferTo(convFile);
return convFile;
}
问题是浏览器不显示图像,但我无法找到错误的地方。
你能帮助我吗? :) 非常感谢。
这是将图像转换为String并显示的方法:
import org.apache.commons.codec.binary.Base64;
public String convertByteArrayImagetoString(){
BASE64Encoder base64Encoder = new BASE64Encoder();
File imagePath = new File(defaultPersonImagePath);
try {
BufferedImage bufferedImage = ImageIO.read(imagePath);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", byteArrayOutputStream);
photoString = "data:image/png;base64," + base64Encoder.encode(byteArrayOutputStream.toByteArray());
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
如果您有疑问,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.