springmvc上傳檔案路徑處理
阿新 • • 發佈:2019-02-04
@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 "上傳成功";
}
這種方法只是自己的一個想法,不一定成熟,希望大神指正。