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

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

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

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

干杯

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

要将其存储在文件系统中,您可以使用Commons File Upload 。 这是一个样本

的pom.xml

   commons-fileupload commons-fileupload ${release.version}   commons-io commons-io ${release.version}  

JSP

 

Spring MVC file upload example

Please select a file to upload :

调节器

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

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

   

我希望这有帮助。