1. 程式人生 > >專案釋出後能訪問到本地的檔案(圖片) (java web專案中讀取本地圖片)

專案釋出後能訪問到本地的檔案(圖片) (java web專案中讀取本地圖片)

在專案中,因為業務需要,使用者上傳的圖片存放在伺服器的D盤中,為了讀取並顯示到頁面上,嘗試了兩種方法:

一  通過流讀取

java程式碼:

  1. @RequestMapping(value = "/seekExperts")    
  2.     @ResponseBody
  3.     public String createFolw(HttpServletRequest request,    
  4.             HttpServletResponse response, Model model) {    
  5.         // response.setContentType("image/*"); 
  6.     PageData pd = new
     PageData();  
  7.     pd = this.getPageData();  
  8.     //取路徑
  9.     String path = pd.getString("path");  
  10.         FileInputStream fis = null;    
  11.         OutputStream os = null;    
  12.         try {    
  13.             fis = new FileInputStream(path);    
  14.             os = response.getOutputStream();    
  15.             int count = 
    0;    
  16.             byte[] buffer = newbyte[1024 * 8];    
  17.             while ((count = fis.read(buffer)) != -1) {    
  18.                 os.write(buffer, 0, count);    
  19.                 os.flush();    
  20.             }    
  21.         } catch (Exception e) {    
  22.             e.printStackTrace();    
  23.         }    
  24.         try
     {    
  25.             fis.close();    
  26.             os.close();    
  27.         } catch (IOException e) {    
  28.             e.printStackTrace();    
  29.         }    
  30.         return"ok";    
  31.     }    

前臺程式碼:
  1. <imgalt="image"id="myImage"style="height:250px;width:400px;"src="defectivemanage/seekExperts.do?path=${var.PATH }"/>
這樣能夠實現,但是如果訪問量很大,需要多次讀取流,所以不建議。

二  通過配置虛擬目錄讀取

開啟tomcat的conf資料夾,在server.xml中的<Host></Host>標籤內加入

  1. <Contextpath="/dataResourceImages"docBase="D:\a"crossContext="true"reloadable="false"debug="0"/>
path是虛擬路徑,docBase為真實路徑

jsp程式碼:

  1. <imgalt="image"id="myImage"style="height:250px;width:400px;"src="/dataResourceImages/GIF1.gif"/>

修改後重啟,就可以看到圖片啦