文件下载

  1. 页面显示超链接
  2. 点击超链接后弹出下载提示框
  3. 完成图片文件下载

分析

  1. 超链接指向的资源如果能够被浏览器解析,则在浏览器中展示,如果不能解析,则弹出下载提示框。不满足需求
  2. 任何资源都必须弹出下载提示框
  3. 使用响应头设置资源的打开方式:
    content-disposition:attachment;filename=xxx

步骤

1.定义页面,编辑超链接href属性,指向Servlet,传递资源名称filename
2.定义Servlet
3.获取文件名称
4.使用字节输入流加载文件进内存
5.指定response的响应头 : content-disposition:attachment; filename=xxx
6.将数据写出到response输出流


download.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <a href="/downloadServlet?filename=1.jpg">图片1</a>
</body>
</html>

DownloadServlet

@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求参数,文件名称
        String filename = request.getParameter("filename");
        //2.使用字节输入流加载文件进内存
        //找到服务器的路径
        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/img/" + filename);

        //用字节流关联
        FileInputStream fis = new FileInputStream(realPath);

        //3,设置response响应头
        //3.1设置响应头类型。content-type
        String mimeType = servletContext.getMimeType(filename);//获取文件mime类型
        response.setHeader("content-type",mimeType);
        
        //3.2设置响应头打开方式content-disposition
        response.setHeader("content-disposition","attachment;filename="+filename);

        //4。将输入流的数据写出到输出流中
        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);
    }
}

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐