2015-09-12 70 views
0

我有运行在Tomcat上的Spring MVC web应用程序。Spring MVC上传文件,然后提供下载链接

我上传文件并将其保存在文件系统的/tmp文件夹中。

然后我需要在视图(Thymeleaf)中显示该文件的链接,以便用户可以通过单击链接下载该文件。怎么做?

我听说过有关配置Tomcat以允许特定的上下文链接到FS上的文件夹,但不知道如何做,或者如果这是唯一的解决方案。请帮忙。

回答

0

这是精确设置为我工作(Tomcat的8,用SpringMVC,引导):

  1. 的server.xml: <Context docBase="C:\tmp\" path="/images" />

  2. 在控制器:

@RequestMapping(value = "addNew", method = RequestMethod.POST) public String createNewsSource(@ModelAttribute("newsSource") NewsSource source, BindingResult result, Model model, @RequestParam("attachment") final MultipartFile attachment) { new NewsSourceValidator().validate(source, result); if (result.hasErrors()) { return "source/addNewSource"; } if (!attachment.isEmpty()) { try { byte[] bytes = attachment.getBytes(); BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(new File("/tmp/" + attachment.getOriginalFilename()))); stream.write(bytes); stream.close(); } catch (Exception e) { e.printStackTrace(); } } source.setLogo("images/" + attachment.getOriginalFilename()); newsSourceService.createNewsSourceIfNotExist(source); return "redirect:/sources/list"; } 正如你所看到的,我将文件保存到/tmp,但在DB(source.setLogo()),我指着图片为server.xml

这里映射在那里我发现了大约Tomcat的配置:

如果图像均位于Web应用程序之外,你想有 Tomcat的DefaultServlet到处理它们,那么你基本上需要做 在Tomcat中到后续上下文元素添加到 /conf/server.xml内标签:

这样,他们就可以通过http://example.com/images/访问....

SO answer to a similar question

1

我的做法,这是略有不同的方式。基本上,我使用两个控制器操作来处理文件上传,一个用于上传和下载(查看)文件。

因此,上传操作会将文件保存到文件系统上的某个预配置目录,我假设您已经有该部分工作。

然后声明类似下载操作这个

@Controller 
public class FileController { 
    @RequestMapping("/get-file/{filename}") 
    public void getFileAction(@RequestParam filename, HttpServletResponse response) { 
     // Here check if file with given name exists in preconfigured upload folder 
     // If it does, write it to response's output stream and set correct response headers 
     // If it doesn't return 404 status code 
    } 
} 

如果你想不可能仅仅通过了解名来下载文件,上传文件后,保存到数据库中的一些元信息(或任何其它存储)并为其分配一些散列(随机ID)。然后,在getFileAction中,使用此散列来查找文件,而不是原始文件名。

最后,我会阻止使用/tmp进行文件上传。它取决于所使用的系统/应用程序,但临时数据一般都是临时目录,正如名称所示。通常保证临时目录中的数据将保持“合理的时间”,但应用程序必须考虑到临时目录的内容可以随时删除。

+0

谢谢。所以基本上你的做法是有一个下载文件的行动。不错的方法,但我认为这是一个开销。为什么不提供链接到文件。然而,Tomcat的上下文方法似乎也使用了Servlet - “DefaultServlet”。我正在使用'/ tmp',仅用于测试目的。 – ACV

+1

我认为,除非zou期待像Facebook这样的流量,否则我认为crating controller的开销并不大。我使用这个,因为我通常会在动作中做更多的检查。 我想你可以使用上下文别名,如果你正在使用tomcat 7,但我没有直接的经验:http://www.we3geeks.org/2012/03/04/tomcat-directory-aliases/注意在tomcat 8中改变了用法:http://stackoverflow.com/questions/25909329/after-migrating-to-tomcat-8-aliases-doesnt-work-any-more – Kejml

+0

好的,这在Tomcat 8中适用于我'<上下文docBase =“C:\ tmp \”path =“/ images”/>' – ACV