文件目录
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方式提交的时候=号后面不能有空格!