文件资源位置:web/img下
HTML页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>学习文件下载</title>
</head>
<body>
<h1>使用超链接</h1>
<a href="/filedown/img/abc.png">图片1</a>
<a href="/filedown/img/aa.flv">视频1</a>
<a href="/filedown/img/奥尼尔.gif">图片2</a>
<hr/>
<a href="/filedown/downServlet?filename=abc.png">图片1</a>
<a href="/filedown/downServlet?filename=aa.flv">视频1</a>
<a href="/filedown/downServlet?filename=奥尼尔.gif">中文图片2</a>
</body>
</html>
Servlet 类
@WebServlet("/downServlet")
public class FileDownServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取请求参数,文件名称
String filename = request.getParameter("filename");
ServletContext context = this.getServletContext();
//找到服务器文件的真实路径
String realPath = context.getRealPath("/img/" + filename);
//使用字节流关联
FileInputStream fis=new FileInputStream(realPath);
/* 设置响应头
响应头类型:content-type
响应头打开方式:content-disposition
*/
String mimeType = context.getMimeType(filename);
response.setHeader("content-type",mimeType);
//获取user-agent请求头
String agent = request.getHeader("user-agent");
//使用工具类方法编码文件名即可
filename = DownLoadUtils.getFileName(agent, filename);
response.setHeader("content-disposition","attachment;filename="+filename);
//将输入流的数据写出到输出流中
ServletOutputStream sos = response.getOutputStream();
byte[] bytes=new byte[1024*8];
int len=0;
while ((len=fis.read(bytes))!=-1){
sos.write(bytes,0,len);
}
fis.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
util工具类:对文件名编码
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;
}
}