建立一个Servlet类:FiledownloadServlet;
package com.lanqiao.javaweb.filedownloadservlet;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLClassLoader;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sun.net.URLCanonicalizer;
public class FiledownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.setContentType("application/x-msdownload"):
//即设置一个响应的类型: application/x-msdownload
//通知客户端浏览器: 这是一个需要下载的文件, 不能再按普通的 html 的方式打开.
response.setContentType("application/x-msdownload");
//response.setHeader("Content-Disposition", "attachment;filename=abc.txt");
//设置用户处理的方式: 响应头: Content-Disposition
//通知客户端浏览器: 不再有浏览器来处理该文件, 而是交由用户自行处理
//.txt为下载文件的类型,必须与后面downloadFileName的类型相同;
String fileName="文件下载.txt";
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//读取进来然后下载;
OutputStream out=response.getOutputStream();
//所读取文件的地址,及类型
String downloadFileName="C:\hh.txt";
//读取要下载的文件
InputStream in=new FileInputStream(downloadFileName);
byte[] buffer=new byte[1024];
int len=0;
while((len=in.read(buffer))!=-1){
out.write(buffer, 0, len);
}
in.close();
}
}
web.xml文件:
<servlet>
<description></description>
<display-name>FiledownloadServlet</display-name>
<servlet-name>FiledownloadServlet</servlet-name>
<servlet-class>com.lanqiao.javaweb.filedownloadservlet.FiledownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FiledownloadServlet</servlet-name>
<url-pattern>/filedownloadServlet</url-pattern>
</servlet-mapping>
download.jsp页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
<!-- 静态下载 -->
<a href="xyz.txt">download xyz.txt</a>
<br><br>
<a href="test.jsp">download test.jsp</a>
<br><br>
<!-- 动态下载 -->
<a href="filedownloadServlet">Download To File</a>
</body>
</html>