0

我需要在 Spring MVC Hibernate Web 应用程序中将图像从 jsp 保存到数据库(MySql)。有人可以给我一个上传图像然后将其保存到数据库中的示例吗?

4

3 回答 3

0

使用任何基于 jquery 的 fileuploaders ,并仅将路径保存在 db 中。这样您就可以快速扩展您的应用程序。例如值上传器

于 2012-07-01T12:08:05.563 回答
0

解决方案是首先从jsp获取路径,并以hibernet传递对象作为参数。

用户车辆.java

private byte[] image;
public UserVehicle(byte[] image)
{
  this.image=image;
}
---getter n setter
}

在 Controller.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 文件插入到您的数据库中。

于 2013-11-27T09:57:25.143 回答
0

使用 Spring MVC,所以你可以像这样使用 spring 形式:

<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",然后您可以为您的休息控制器添加 multipart 参数,如下所示:

@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";
}

最后,您需要像这样在 spring 上下文中创建 multipart 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 应用程序中通常使用这种方式来上传文件,所以我希望你也需要。

于 2019-04-12T14:37:36.550 回答