2013-05-20 2 views
0

Я использую Spring 3.2, Hibernate 4.1 и Mysql. Я пытаюсь сохранить файл на локальном диске, а затем сохранить путь к файлу базы данных, который будет использоваться для последующей загрузки. Я внедрил загрузку файла на сервер, но теперь я не уверен, кто должен сохранить путь к файлу в таблице mysql.Spring inserting filepath to 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`); 

Путь к файлу должен быть вставлен в колонну document_path. Любые мысли приветствуются.

+1

чем проблема? Где вы застряли? –

+0

Спасибо, что ответили. Мне интересно, как теперь сохранить путь к файлу, который я загрузил в таблицу базы данных. – user2259555

ответ

0

Во-первых, module_id создается базой данных, поэтому вы не должны принимать его с лицевой стороны. Что, если я отправлю module_id как 24, когда вы ожидаете, что следующая запись в БД составляет 30?

Теперь код:

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