public class DownloadFile extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
// response.setContentType("text/html;charset=utf-8");
String filename = request.getParameter("filename");
String realPath = this.getServletContext().getRealPath("/WEB-INF/download");
String filepath= realPath+"/"+filename;
//设置浏览器响应体文件类型
String mimeType = request.getServletContext().getMimeType(filename);
response.setContentType(mimeType);
//附件
//解决文件名中文乱码问题
String header = request.getHeader("User-Agent");
if(header != null && header.contains("Firefox")) {
filename = "=?utf-8?B?"+new BASE64Encoder().encode(filename.getBytes("utf-8"))+"?=";
}else {
filename = URLEncoder.encode(filename, "UTF-8");
}
response.setHeader("Content-Disposition", "attachment; filename="+filename);
FileInputStream fis=new FileInputStream(filepath);
ServletOutputStream ops=response.getOutputStream();
byte b[]=new byte[1024];
while(fis.read(b)!=-1)
{
ops.write(b);
}
fis.close();
ops.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
<a href="${pageContext.request.contextPath}/DownloadFile?filename=阎维文.pdf">p.pdf</a>