文件下载
最重要的两点是设置响应头
1、设置contextType 响应头:通知客户端这是个下载文件
response.setContentType("application/x-msdownload");
2、设置content=Disposition 响应头:通知浏览器不再由自己自行处理要下载的文件,而是由客户自己下载
response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <% 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>My JSP 'index.jsp' starting page</title> </head> <body> <a href="downLoadServlet">Study download</a> </body> </html>
servlet
package com.future.demo; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.URLEncoder; 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 { //设置contextType 响应头:通知客户端这是个下载文件 response.setContentType("application/x-msdownload"); //获取要下载的文件名字 String fileName = "文件下载.txt"; //设置content=Disposition 响应头:通知浏览器不再由自己自行处理要下载的文件,而是由客户自己下载 response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8")); OutputStream os = response.getOutputStream();//不需要主动关流,是要用户自动处理的 //要下载的文件 InputStream is = new FileInputStream("C:\\Users\\Administrator\\Desktop\\ms.txt"); int len = 0; byte[] buffer = new byte[1024]; while((len=is.read(buffer))!=-1){ os.write(buffer, 0, len); } is.close(); //os.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }