Servlet代码:
public class ResponseFileServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
downfile(response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
downfile(response);
}
private void downfile(HttpServletResponse response) throws IOException {
//获取下载的文件路径(注意获取这里获取的是绝对路径,先获取ServletContext再使用ServletContext的getRealPath方法获取绝对路径)
String path = this.getServletContext().getRealPath("/Resourse/Student.xml");
//设置响应头控制浏览器以下载的形式打开文件
response.setHeader("content-disposition",
"attachment;fileName="+"Student.xml");
InputStream in = new FileInputStream(path); //获取下载文件的输入流
int count =0;
byte[] by = new byte[1024];
//通过response对象获取OutputStream流
OutputStream out= response.getOutputStream();
while((count=in.read(by))!=-1){
out.write(by, 0, count);//将缓冲区的数据输出到浏览器
}
in.close();
out.flush();
out.close();}}
从上面代码可以看出使用Response实现文件下载思路主要分为:
先获取下载文件的绝对路径,再设置响应头(content-disposition)表示告知浏览器要以下载的形式打开文件,然后使用InputStream获取下载的文件的输入流,创建数据缓冲区,通过response对象获取OutputStream流,将FileInputStream流写入byte数组,使用OutpuStream将byte数组的数据输出到浏览器。
运行结果:
下载文件名称带有中文的文件,需要在下面设置响应头那里使用URLEncoder.encode方法设置编码,避免文件名乱码,代码如下
//下载带有中文名称的文件
response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode("IO笔记.txt","UTF-8"));
效果