Controller獲得上傳檔案的絕對路徑
阿新 • • 發佈:2019-01-02
@RequestMapping(value = "/upload", method = RequestMethod.POST) public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response) throws Exception { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd/HH"); /** 構建檔案儲存的目錄* */ String logoPathDir = "/business/shops/upload/" + dateformat.format(new Date()); /** 得到檔案儲存目錄的真實路徑* */ String logoRealPathDir = request.getSession().getServletContext() .getRealPath(logoPathDir); /** 根據真實路徑建立目錄* */ File logoSaveFile = new File(logoRealPathDir); if (!logoSaveFile.exists()) logoSaveFile.mkdirs(); /** 頁面控制元件的檔案流* */ MultipartFile multipartFile = multipartRequest.getFile("file"); /** 獲取檔案的字尾* */ String suffix = multipartFile.getOriginalFilename().substring( multipartFile.getOriginalFilename().lastIndexOf(".")); /** 使用UUID生成檔名稱* */ String logImageName = UUID.randomUUID().toString() + suffix;// 構建檔名稱 /** 拼成完整的檔案儲存路徑加檔案* */ String fileName = logoRealPathDir + File.separator + logImageName; File file = new File(fileName); try { multipartFile.transferTo(file); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } /** 打印出上傳到伺服器的檔案的絕對路徑* */ System.out.println("****************"+fileName+"**************"); insertDate(fileName); return new ModelAndView("redirect:/business/shops/my.jsp"); }