JSP 獲取本地圖片的實例詳解
IE當前7以上版本不支持直接在src上寫本地硬盤地址來顯示圖片。因為我們只有通過后臺在response中讀到二進制流的方式來在前臺顯示圖片。
具體代碼如下:
public void showPicture(){ String id = ServletActionContext.getRequest().getParameter("id");//前臺傳來的存圖片路徑實體類的主鍵id HttpServletResponse response = ServletActionContext.getResponse();//struts2獲取response if(id != null && !"".equals(id)){ this.classicCases = this.classicCasesManager.findClassicCasesById(id); String pic_path = this.classicCases.getImagesLocalPath();//圖片路徑 FileInputStream is; try { is = new FileInputStream(pic_path); int i = is.available(); // 得到文件大小 byte data[] = new byte[i]; is.read(data); // 讀數據 is.close(); response.setContentType("image/*"); // 設置返回的文件類型 OutputStream toClient = response.getOutputStream(); // 得到向客戶端輸出二進制數據的對象 toClient.write(data); // 輸出數據 toClient.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
jsp頁面很簡單,路徑格式為,http://localhost:8080/projectName/*.action:prama=XXX
<img alt="" id="images" src="<%=basePath %>ClassicCasesAction!showPicture.action?id=${classicCases.id}">
如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答