在Spring MVC中将图像上传到服务器并在mysql数据库中存储引用 [英] uploading images to server in spring MVC and storing reference in mysql database

查看:395
本文介绍了在Spring MVC中将图像上传到服务器并在mysql数据库中存储引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm coding a Spring MVC 3.0 application with Tomcat as the web server.

我们的要求是让用户上传图片。我正在考虑将这个图像存储在磁盘文件系统中,并将参考路径存储在MySQL中,而不是将所有文件信息存储在MySQL数据库中作为BLOB(我被告知存储在MySQL中不是最佳实践)。

Our requirement is to let the user upload an image. I'm thinking of storing this image on the disk file system and store the reference path in MySQL instead of storing all the file info in MySQL database as BLOB (I was told storing in MySQL is not best practice).

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

Can any one recommend how to do this in Spring MVC?

干杯

推荐答案

存储在磁盘中并存储在MySQL中有一些警告。 这里是一个很好的讨论。

Storing in disk and storing in MySQL has its on caveats. Here is good discussion about it.

要将其存储在文件系统中,您可以使用 Commons文件上传。以下是一个示例

To store it in file system you can use Commons File Upload. Here is a sample

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.
 }  
}

并在您的应用程序上下文中定义

And define this in your application context

 <bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

我希望这有帮助。

这篇关于在Spring MVC中将图像上传到服务器并在mysql数据库中存储引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆