標籤:java web
在網頁上,如果我們的超連結的地址對應的是一個jpg檔案,txt檔案等,點選連結時,瀏覽器預設的是開啟這些檔案而不是下載,那麼如何才能實現預設下載呢。
可通過自己寫一個download.jsp來實現。
<span style="font-size:18px;"><%@ page contentType="text/html; charset=UTF-8"%><%@ page import="java.net.*"%><%//得到檔案名稱字和路徑 String filename = request.getParameter("filename");String filepath = request.getParameter("filepath");String displayfilename = URLEncoder.encode(filename,"UTF-8");try {response.setContentType("application/x-download");response.setHeader("Content-Disposition","attachment;filename=\"" + displayfilename + "\""); RequestDispatcher dis = application.getRequestDispatcher(filepath + filename); if (dis != null) { dis.forward(request,response); } response.flushBuffer();} catch (Exception e) { System.out.println("下載取消:" + filepath + filename);} out.clear(); out = pageContext.pushBody();%></span>當我們要連結圖片(或其他瀏覽器預設開啟的格式,這裡以圖片為例)時,把對應的檔案名稱和地址傳入download.jsp的filename和filepath參數裡,具體寫法如下
<a class="blue-line-a" href=" /PackTool/download.jsp?filename=WinGUI.exe&filepath=http://127.0.0.1:8080/shareFolder/other/WinGUI.exe">/other/WinGUI.exe</a>
通過這樣方式,我們就能實現檔案的預設下載了,而不是瀏覽器的預設開啟。
圖片實現預設下載而不是開啟圖片(Java版)