码迷,mamicode.com
首页 > 其他好文 > 详细

文件下载小案例

时间:2020-01-21 00:48:46      阅读:52      评论:0      收藏:0      [点我收藏+]

标签:class   while   tac   获取文件   ref   stream   div   gets   jpg   

 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>

文件下载小案例

标签:class   while   tac   获取文件   ref   stream   div   gets   jpg   

原文地址:https://www.cnblogs.com/bozhengheng/p/12219801.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!