1. 用jsp頁面實現了文件的下載: html
<%@page language="java" contentType="application/x-msdownload" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <%@ page language="java" import="java.io.*"%> <%@ page language="java" import="java.net.URLEncoder"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>下載文件</title> </head> <body> <% String docname = request.getParameter("docname"); String filedisplay = ""; //因爲href連接不能使用中文,這裏根據文件名判斷是否須要改成中文 if (docname.equals("txt.txt") || docname.equals("word.doc") || docname.equals("excel.xls")) { filedisplay = "好友信息" + docname.substring(docname.lastIndexOf(".")); } else { filedisplay = docname;//"給用戶提供的下載文件名"; } response.reset();//能夠加也能夠不加 response.setContentType("application/x-download"); String paths = pageContext.getServletContext().getRealPath("/"); String realPath = paths + "/download/"; String filedownload = realPath + docname; filedisplay = URLEncoder.encode(filedisplay, "UTF-8"); response.addHeader("Content-Disposition", "attachment;filename=" + filedisplay); //此處記得清理下。在釋放在jsp中使用的對象時,會調用response.getWriter(),由於這個方法是和response.getOutputStream()相沖突的! out.clear(); out = pageContext.pushBody(); OutputStream outp = null; FileInputStream in = null; try { outp = response.getOutputStream(); in = new FileInputStream(filedownload); byte[] b = new byte[1024]; int i = 0; while ((i = in.read(b)) > 0) { outp.write(b, 0, i); } outp.flush(); } catch (Exception e) { System.out.println("Download Error!"); e.printStackTrace(); } finally { if (in != null) { in.close(); in = null; } if (outp != null) { outp.close(); outp = null; } } %> </body> </html>
2.添加相關的下載連接,後面跟的參數是下載文件名。例如: java
<a href="../download/down.jsp?docname=soplus.apk" >下載</a>