2013-05-20 48 views
0

我使用Spring 3.2,Hibernate 4.1和Mysql。我试图将文件保存到本地驱动器,然后将文件路径保存到数据库以供将来下载。我已经实现了文件上传到服务器,但现在我不知道谁去保存到MySQL表的文件路径。Spring将文件路径插入到mysql

这是控制器代码

@RequestMapping(value = "/add", method = RequestMethod.POST, params = "save") 
public String saveProcess(@RequestParam("moduleId") Integer moduleId, 

@ModelAttribute("module") Module module, BindingResult result, 
@RequestParam("file") CommonsMultipartFile[] file , 
HttpSession session, HttpServletRequest request) throws 

IllegalStateException, IOException { 
    logger.info("Request to save the module"); 

    if(module != null){ 

    if (file != null && file.length > 0) { 
     for (CommonsMultipartFile aFile : file){ 

      System.out.println("Saving file: " + aFile.getOriginalFilename()); 

      if (!aFile.getOriginalFilename().equals("")) { 
       aFile.transferTo(new File(saveDirectory +  

      aFile.getOriginalFilename())); 
      } 
     } 
    } 


    moduleService.saveorupdate(module); 

} 
    return "redirect:/home"; 
} 

这是分贝

CREATE TABLE `modules` (
`module_id` bigint(20) NOT NULL AUTO_INCREMENT, 
`document_title` varchar(255) DEFAULT NULL, 
`document_path` varchar(255) DEFAULT NULL, 
PRIMARY KEY (`module_id`); 

的filepath是要被插入到所述document_path柱。任何想法都会受到欢迎。

+1

什么问题?你卡在哪里? –

+0

感谢您的回复。我想知道如何保存我上传到数据库表的文件的文件路径。 – user2259555

回答

0

首先,module_id由数据库生成,所以您不应该从前端接受它。如果我希望数据库中的下一个条目是30,那么将module_id发送为24会怎样?

现在代码:

@RequestMapping(value = "/add", method = RequestMethod.POST, params = "save") 
public String saveProcess(@RequestParam("moduleId") Integer moduleId, @ModelAttribute("module") Module module, BindingResult result, @RequestParam("file") CommonsMultipartFile[] file) throws IllegalStateException, IOException { 
    logger.info("Request to save the module"); 

    if(module != null) { // No need for the check. Spring guarantees a non null object if it is expected to be a @ModelAttribute. 

    if (file != null && file.length > 0) { 
     for (CommonsMultipartFile aFile : file){ 
      Module module = new Module(); //only one file or more? If one then use the @ModelAttribute module. 

      if (!"".equals(aFile.getOriginalFilename())) { // Best practice to check equals in reverse to avoid potential NullPointerExceptions. 
       File file = new File(saveDirectory + aFile.getOriginalFilename()); 
       aFile.transferTo(file); 
       module.setDocumentTitle(aFile.getOriginalFilename()); 
       module.setDocumentPath(file.getAbsolutePath()); 
       module = moduleService.saveorupdate(module); // return module or id so that you can set it and pass it to the view. 
      } 
     } 
    } 
    } 
    return "redirect:/home"; 
}