Java實現將圖片上傳到webapp路徑下 路徑獲取方式
將圖片上傳到webapp路徑下 路徑獲取方式
此方法獲取到工程webapp文件夾下
String contexPath= request.getSession().getServletContext().getRealPath("/");
獲取IP地址端口號以及項目名稱
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
spring java 獲取webapp下文件路徑
@RequestMapping("/act/worldcup_schedule_time/imgdownload") @ResponseBody public String scheduleDownload(HttpServletRequest request, HttpServletResponse response, HttpSession session) { response.setCharacterEncoding("UTF-8"); String downLoadName = "worldcup.jpg"; InputStream input = null; try { request.setCharacterEncoding("UTF-8"); //獲取文件的路徑 // String url = session.getServletContext().getRealPath("/") + "resources\\images\\act\\worldcup_merge\\worldcup720.png"; String url = session.getServletContext().getRealPath("/") + "resources/images/act/worldcup_merge/worldcup720.png"; System.out.println(url); File file = new File(url); input = FileUtils.openInputStream(file); byte[] data = IOUtils.toByteArray(input); //System.out.println("文件名:"+downLoadName); response.reset(); //設置響應的報頭信息(中文問題解決辦法) response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode(downLoadName, "UTF-8")); response.addHeader("Content-Length", "" + data.length); response.setContentType("image/png; charset=UTF-8"); IOUtils.write(data, response.getOutputStream()); } catch (Exception e) { logger.error("下載圖片出錯"); if (input != null) { IOUtils.closeQuietly(input); } } return null; }
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。