我需要在Spring MVC HibernateWeb应用程序中将图像从jsp保存到数据库(MySql)。有人可以给我一个上传图像然后将其保存到数据库中的示例吗?
使用任何基于 jquery 的文件上传器,并将路径保存在数据库中。 这样您就可以快速扩展您的应用程序。 e..G Valum 上传器
解决方案是首先从 jsp 获取路径,并使用 hibernet pass 对象作为参数。
用户车辆.java
private byte[] image;
public UserVehicle(byte[] image)
{
this.image=image;
}
---getter n setter
}
在控制器中.java
File file = new File(/*your file path*/);
byte[] bFile = new byte[(int) file.length()];
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
UserVehicle user = new UserVehicle(bFile)
你的值将作为 Blob 文件插入到数据库中。
MVC,所以你可以像这样使用 Spring Form:
<form:form method="POST" action="/spring-mvc-xml/uploadFile" enctype="multipart/form-data">
<table>
<tr>
<td><form:label path="file">Select a file to upload</form:label></td>
<td><input type="file" name="file" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
最重要的部分是添加 enctype="multipart/form-data",输入的类型必须是"file",然后你可以为 rest 控制器添加多部分参数,如下所示:
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String submit(@RequestParam("file") MultipartFile file, ModelMap
modelMap) {
// here u can find your uploaded file you can set the prop in your
object model ,then save object and this will save the file also in
blob.
return "fileUploadView";
}
最后,您需要在春季上下文中像这样将多部分 Bean 装箱:
//you can defined it in xml way if your configuration in xml file
@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver()
{
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(20848820);
return multipartResolver;
}
并且您还需要将依赖处的上传文件库添加到 Spring 可以使用它:
dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version> // or you can find the last version
</dependency>
最后注意:对于数据库,您可以将列设置为 BLOB 或任何 LOB 类型。我通常使用这种方式在我的 Spring 应用程序中上传文件,所以我希望您也需要。