页面请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/wen_jianServlet?filename=1.png">图片</a>
</body>
</html>
servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取请求参数;文件名称
String filename = request.getParameter("filename");
// 获取文件真实路径
ServletContext servletContext = this.getServletContext();
String realPath = servletContext.getRealPath("/image/" + filename);
// 根据路径获取输入流
FileInputStream fileInputStream = new FileInputStream(realPath);
// 设置响应头类型:context-type,content-disposition
response.setHeader("context-type",servletContext.getMimeType(filename));
response.setHeader("content-disposition","attachment;filename="+filename);
// 将输入流的数据写入到输出流中
ServletOutputStream outputStream = response.getOutputStream();
byte[] buffer =new byte[1024*8];
while (fileInputStream.read(buffer)!=-1){
outputStream.write(buffer,0,buffer.length);
}
// 关闭输入流,输出流不用关闭
fileInputStream.close();
}
存在问题
中文文件名不显示:
解决:
获取客户端使用的浏览器请求头:user-agent
使用工具类编码文件名:DownLoadUtils.getFileName(agent,filename);