<分区>
我正在使用 Tomcat 作为 Web 服务器编写 Spring MVC 3.0
应用程序。
我们的要求是让用户上传一张图片。我正在考虑将此图像存储在磁盘文件系统上并将引用路径存储在 MySQL 中,而不是将所有文件信息作为 BLOB 存储在 MySQL 数据库中(有人告诉我存储在 MySQL 中不是最佳做法)。
任何人都可以推荐如何在 Spring MVC 中执行此操作吗?
干杯
<分区>
我正在使用 Tomcat 作为 Web 服务器编写 Spring MVC 3.0
应用程序。
我们的要求是让用户上传一张图片。我正在考虑将此图像存储在磁盘文件系统上并将引用路径存储在 MySQL 中,而不是将所有文件信息作为 BLOB 存储在 MySQL 数据库中(有人告诉我存储在 MySQL 中不是最佳做法)。
任何人都可以推荐如何在 Spring MVC 中执行此操作吗?
干杯
最佳答案
存储在磁盘中和存储在 MySQL 中有一些注意事项。 Here是很好的讨论。
要将其存储在文件系统中,您可以使用 Commons File Upload .这是一个示例
pom.xml
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${release.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${release.version}</version>
</dependency>
JSP
<h2>Spring MVC file upload example</h2>
<form method="POST" action="<c:url value='/upload' />"
enctype="multipart/form-data">
Please select a file to upload : <input type="file" name="file" />
<input type="submit" value="upload" />
</form>
Controller
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handleFormUpload(
@RequestParam("file") MultipartFile file) throws IOException{
if (!file.isEmpty()) {
BufferedImage src = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
File destination = new File("File directory with file name") // something like C:/Users/tom/Documents/nameBasedOnSomeId.png
ImageIO.write(src, "png", destination);
//Save the id you have used to create the file name in the DB. You can retrieve the image in future with the ID.
}
}
并在您的应用程序上下文中定义它
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
希望对您有所帮助。
关于java - 在 spring MVC 中将图像上传到服务器并将引用存储在 mysql 数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14085511/