【问题标题】:Store image in h2 database将图像存储在 h2 数据库中
【发布时间】:2017-07-24 07:15:48
【问题描述】:

我正在使用 Spring MVC 架构和使用 H2 数据库的 Hibernate。

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add New Product</title>
</head>
<body>

<p>Add New Product !!</p>
<form:form action="addProducttoDB" commandName="product" method="POST" enctype="multipart/form-data">
Product id :<br>
<label>Product Name : </label><form:input  path="product_name" value="Product Name"/> <br>
Product Desc : <form:input path="product_desc" value="Product Desc"/><br>
Select Image :<form:input type="file" path=""/><br> 
Submit : <input type="submit" value="Add">
</form:form>

</body>
</html>

如上面的代码 - 它存储有关产品的信息并使用操作请求添加到数据库 -> "addProducttoDB" ,模型对象 -> 产品

路径是列名,现在我想保存一张图片和详细信息。我该怎么做?

【问题讨论】:

    标签: java hibernate jsp spring-mvc h2


    【解决方案1】:

    您需要进行以下更改

    • &lt;form:input type="file" path="productImg" name="productImg/&gt;命名
    • 在数据存储逻辑所在的方法签名中声明 MultipartFile 对象
    • 在 save 方法中调用 savesaveMultipartFile 方法

    方法

    private void saveMultipartFile( MultipartFile files)
    {
        if(!files.isEmpty()){
            try {
                String fileName = files.getOriginalFilename();
                String dirLocation ="Path where you want to save image";
                if(!new File(dirLocation).exists()){
                    File file = new File(dirLocation);
                    file.mkdirs();
                }
                byte[] bytes = files.getBytes();
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(dirLocation+new File(fileName)));
                bufferedOutputStream.write(bytes);
                bufferedOutputStream.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-06
      • 2012-10-17
      • 2017-06-16
      • 2011-04-15
      • 2011-05-07
      • 1970-01-01
      相关资源
      最近更新 更多