我正在使用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>
与上述代码一样 - 它存储有关产品的信息并使用操作请求添加到数据库 - &gt; “addProducttoDB”,模型对象 - &gt;产品
路径是列名,现在我想保存图像和细节。我怎么能这样做?
答案 0 :(得分:0)
您需要进行以下更改
<form:input type="file" path="productImg" name="productImg/>
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();
}
}
}