4

我正在编写一个Spring MVC 3.0使用 Tomcat 作为 Web 服务器的应用程序。

我们的要求是让用户上传一张图片。我正在考虑将此图像存储在磁盘文件系统上并将参考路径存储在 MySQL 中,而不是将 MySQL 数据库中的所有文件信息存储为 BLOB(有人告诉我存储在 MySQL 中不是最佳做法)。

任何人都可以推荐如何在 Spring MVC 中执行此操作吗?

干杯

4

1 回答 1

13

存储在磁盘中和存储在 MySQL 中都有一些注意事项。是关于它的很好的讨论。

要将其存储在文件系统中,您可以使用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>

控制器

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

我希望这有帮助。

于 2012-12-30T04:19:42.323 回答