**
ServletContext对象实现文件下载
**
使用request和response以及servletcontext来实现文件的下载功能。
1.编写静态网页download.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件下载</title>
</head>
<body>
<a href="/0826/downLoadServlet?filename=1.jpg">图片1</a>
<a href="/0826/downLoadServlet?filename=2.jpg">图片2</a>
</body>
</html>
2.进行servlet类的编写,使用注解的方式配置web.xml
package cn.lsf.down;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
@WebServlet("/downLoadServlet")
public class DownLoadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取请求参数,文件名称
String filename=request.getParameter("filename");
//使用字节输入流加载文件进内存
//找到文件服务器路径
ServletContext servletContext = this.getServletContext();
String realPath = servletContext.getRealPath("/img/" + filename);
//用字节流关联
FileInputStream inputStream = new FileInputStream(realPath);
//设置response的响应头
String mimeType = servletContext.getMimeType(filename);
response.setHeader("content-type",mimeType);
//解决中文乱码问题
String header = request.getHeader("user-agent");
//使用工具类方法编码文件
filename = DownLoadUtils.getFileName(header, filename);
//设置响应头类型
response.setHeader("content-disposition","attachment;filename="+filename);
//将输入流的数据写出到输出流中
ServletOutputStream outputStream = response.getOutputStream();
byte[] buffer=new byte[1024*8];
int len=0;
while ((len=inputStream.read(buffer))!=-1){
outputStream.write(buffer,0,len);
}
inputStream.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
3.工具类的编写
package cn.lsf.down;
import sun.misc.BASE64Encoder;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class DownLoadUtils {
public static String getFileName(String agent, String filename) throws UnsupportedEncodingException {
if (agent.contains("MSIE")) {
// IE浏览器
filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+", " ");
} else if (agent.contains("Firefox")) {
// 火狐浏览器
BASE64Encoder base64Encoder = new BASE64Encoder();
filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
} else {
// 其它浏览器
filename = URLEncoder.encode(filename, "utf-8");
}
return filename;
}
}