1. 程式人生 > >javaWeb實現檔案下載

javaWeb實現檔案下載

今天學習了JavaWeb實現檔案下載,為了以後方便查詢並讓需要的人學習,今兒把程式碼獻上!!!!大笑

首先寫一個jsp頁面

字型加粗的為主要內容:

download.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>檔案下載</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	
  </head>
  
  <body>
  	<a href="/download/DownloadServlet?filename=1.jpg">檔案下載</a>
</body> </html>

然後在定義一個Servlet,如下:

DownloadServlet:

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setCharacterEncoding("UTF-8");
		//設定ContentType欄位值
		response.setContentType("text/html;charset=utf-8");
		//獲取所要下載的檔名稱
		String filename = request.getParameter("filename");
		//下載檔案所在目錄
		String folder = "/filename/";
		//通知瀏覽器以下載的方式開啟
		response.addHeader("Content-type", "appllication/octet-stream");
		response.addHeader("Content-Disposition", "attachment;filename="+filename);
		//通知檔案流讀取檔案
		InputStream in = getServletContext().getResourceAsStream(folder+filename);
		//獲取response物件的輸出流
		OutputStream out = response.getOutputStream();
		byte[] buffer = new byte[1024];
		int len;
		//迴圈取出流中的資料
		while((len = in.read(buffer)) != -1){
			out.write(buffer,0,len);
		}
		
		
	}

效果圖:


用到的架包:commons-fileupload-1.3.1.jar、commons-io-2.4.jar