protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取请求参数,文件名称 String filename = request.getParameter("filename"); //2.使用字节输入流加载文件 //2.1找到文件服务器路径 ServletContext sc = this.getServletContext(); String realPath = sc.getRealPath("/img/"+filename); System.out.println(realPath); //2.2用字节流关联 FileInputStream is = new FileInputStream(realPath); //3.定义输出流 ServletOutputStream sos = response.getOutputStream(); //4.1获取响应头response //4.1.1获取文件的类型,使用servletcontext.getMimeType String mimeType = sc.getMimeType(filename); //4.2设置响应头类型:content-type response.setHeader("content-type",mimeType); //4.3设置响应头content-disposition response.setHeader("content-disposition","attachment;filename="+filename); //4.定义缓冲区 byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1){ sos.write(bytes); } is.close(); }
<html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="/day15/img/1.jpg">图片1</a> <a href="/day15/img/2.jpg">图片2</a> <hr/> <a href="/day15/downServlet?filename=1.jpg">图片1</a> <a href="/day15/downServlet?filename=2.jpg">图片2</a> </body> </html>
原文地址:https://www.cnblogs.com/bozhengheng/p/12219801.html
时间: 2024-11-13 07:56:21