I'm using Spring 3.2, Hibernate 4.1 and Mysql. I'm trying to save a file to the local drive and then save the filepath to the database to be used for future download. I have implemented the file upload to server but now I'm not sure who to go about saving the file path to the mysql table.
This is the controller code
@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";
}
This is the db
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`);
The filepath is to be inserted into the document_path column. Any thoughts would be welcome.
解决方案
First, the module_id is generated by the database, so you shouldn't be accepting it from the front end. What if I send module_id as 24 when you expect the next entry in the DB is 30?
Now the code:
@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";
}