java線上預覽pdf檔案或圖片檔案
阿新 • • 發佈:2019-01-02
在專案中需要使用到線上瀏覽檔案功能,由於專案中只能上傳pdf和圖片檔案,所有就只做了預覽pdf和圖片的功能。
在頁面中的程式碼如下:
<a onclick="show(show_attach?filePath="+path+"&type="+type+")">檢視</a>
path:是檔案存放在伺服器上的位置
type:是檔案的型別
js中也就只有一個開啟新頁面的功能,程式碼如下:
function show(location){
window.open(location);
}
java後臺處理程式碼如下:
@RequestMapping(value="/show_attach",method=RequestMethod.GET,produces = "application/json;charset=UTF-8") public void show_attach(HttpServletRequest request,HttpServletResponse response){ FileInputStream bis = null; OutputStream os = null; try { String path = request.getParameter("filePath");//網路圖片地址 response.setContentType("text/html; charset=UTF-8"); String type = request.getParameter("type"); if("pdf".equalsIgnoreCase(type)){ response.setContentType("application/pdf"); }else{ response.setContentType("image/"+type); } bis = new FileInputStream(path); os = response.getOutputStream(); int count = 0; byte[] buffer = new byte[1024 * 1024]; while ((count =bis.read(buffer)) != -1){ os.write(buffer, 0,count); } os.flush(); }catch (Exception e) { e.printStackTrace(); } finally { if (os !=null){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (bis !=null){ try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
以上就完成了對pdf和圖片的線上開啟;由於瀏覽器的差異,有些瀏覽器可能會彈出下載提示框。