这里讨论数据库里保存的路径的相关处理,上传过程省略,可参考http://blog.csdn.net/cheung1021/article/details/7084673/
目标希望保存在项目的webapp的resources/images/upload目录下
@RequestMapping(value = "upload", method = RequestMethod.POST)
@ResponseBody
public Object uploadImg(MultipartFile file, HttpServletRequest request) throws Exception {
// String basePath = request.getSession().getServletContext().getRealPath("upload");
//如果这样写,路径中会带有盘符D:*****,保存到数据库时应该保存为相对地址,所以不应该这样写
String basePath = "src/main/webapp/resources/images/upload/";//如果写为"/项目名、resources/images/***"则也是保存在该盘的根目录下,所以这里写项目的相对路径,但是在保存数据库时进行路径的截取
Calendar calendar = Calendar.getInstance();
String year = calendar.get(Calendar.YEAR) + "";
String month = calendar.get(Calendar.MONTH) + "";
String uploadTargetPath = basePath + year + month + "/"; //文件目录地址,年月作为文件夹名称
String originalFileName = file.getOriginalFilename();
String fileType = originalFileName.substring(originalFileName.indexOf(".") + 1);
logger.info("------------>>>>" + fileType);
String newFileName = UUID.randomUUID().toString() + "." + fileType;
File targetFile = new File(uploadTargetPath, newFileName);
if(!targetFile.exists()) {
new File(uploadTargetPath).mkdirs();
}
String pathForDb = uploadTargetPath.substring(uploadTargetPath.indexOf("resources"));//截取希望保存到数据库的路径
UploadFileDto fileDto = new UploadFileDto(BG_IMG_KEY, originalFileName,
newFileName, pathForDb + newFileName, fileType);
systemService.addOrUpdateImg(fileDto);
file.transferTo(targetFile);
return "上传成功";
}
这种方法只是自己的一个想法,不一定成熟,希望大神指正。