1. 程式人生 > >用servlet寫的一個簡單的下載檔案功能

用servlet寫的一個簡單的下載檔案功能


檔案目錄

download.html原始碼

<span style="font-family:KaiTi_GB2312;font-size:18px;"><strong><!doctype html>
<html>
<head>
<meta charset="gb2312">
<title>下載</title>
</head>

<body>
<form action="" method="post">
mp3檔案 <a href="/DownloadFile/servlet/DownloadServlet?filename=shuizhonghua.mp3">點選下載</a><br/>
text檔案 <a href="/DownloadFile/servlet/DownloadServlet?filename=mytest.txt">點選下載</a><br/> <br/>
jpg檔案<a href="/DownloadFile/servlet/DownloadServlet?filename=kulou.jpg">點選下載</a><br/> <br/>
</form>
</body>
</html>
</strong></span>
DownloadServlet原始碼
<span style="font-family:KaiTi_GB2312;font-size:18px;"><strong>package com.ttf.download;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html; charset = gb2312");
		//out.println("hello");
		//得到get方式提交的那個filename
		String fileName = request.getParameter("filename");
		System.out.println(fileName);
		//表明是要下載檔案
		response.setHeader("Content-Disposition", "attachment; filename="+fileName);
		//得到伺服器裡檔案的真是地址
		String path = this.getServletContext().getRealPath("/file/"+fileName);
		//System.out.println(path);
		//一個二進位制輸入流
		FileInputStream fis = new FileInputStream(new File(path));
		byte[] b = new byte[1024];
		int length;
		OutputStream out = response.getOutputStream();
		while((length = fis.read(b)) > 0) {
			out.write(b, 0, length);//寫出
		}
		
		out.flush();
		out.close();
		fis.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}</strong></span>

需要注意的是

<a href="/DownloadFile/servlet/DownloadServlet?filename=shuizhonghua.mp3">
模擬get方式提交的時候=號後面不能有空格!