java - 在 spring MVC 中将图像上传到服务器并将引用存储在 mysql 数据库中

标签 java mysql spring spring-mvc blob

<分区>

我正在使用 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/

相关文章:

mysql xampp突然无法启动

spring boot tomcat外部属性文件

spring - 在 Spring Framework 5.1 中注册同名测试 bean

java - 当您在其中调用另一个方法时,方法的执行流程是否等待?

java - Jodatime 的 DateTime 的默认日期时区为 UTC

java - 无法完成 MapActivity

mysql - 如何使用MySQL检查数据库中是否已经存在表?

java - Eclipse 中未处理的异常类型 IOException

mysql - 使用连接创建 View

java - hibernate 异常 : Could not obtain transaction-synchronized Session for current thread