编写html页面,编辑超链接 href 属性,指向Servlet并传递要下载的文件名及格式
Servlet:*获取文件名称
*使用字节输入流加载文件进内存
*指定 response 的响应头:content-disposition:attachmement;filename=xxx
*将数据写出到 response 输出流
html a标签格式
href=”/day15/downloadServlet?filename=鬼刀.png”
Servlet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| @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 fis = new FileInputStream(realPath);
String mimeType = servletContext.getMimeType(filename); response.setHeader("content-type",mimeType); String agent = request.getHeader("user-agent"); String fileName = DownLoadUtils.getFileName(agent, filename); response.setHeader("content-disposition","attachment;filename="+fileName);
ServletOutputStream sos = response.getOutputStream(); byte[] buff = new byte[1024 * 8]; int len = 0; while ((len = fis.read(buff))!=-1){ sos.write(buff,0,len); } fis.close(); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); } }
|
注:解决中文文件名下载不能正常显示问题,需要用到 DownLoadUtils 类获取浏览器编码方式,百度搜索下载即可。