文件下载

public class DownLoadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(1234567890);
        //获取资源的路径
//        String realPath = this.getServletContext().getRealPath("/1.png");
        String realPath = "E:\\Intellij\\我的项目 集合\\responsedownload\\target\\classes\\1.png";
        //获取资源名称
        String fileName = realPath.substring(realPath.lastIndexOf("/") + 1);
        //fileName = "1.png";
        //设置下载的头
        //resp.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("gb2312"), "ISO-8859-1"));
        resp.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));
        //获取下载文件的输入流
        FileInputStream in = new FileInputStream(realPath);
        int len = 0;
        //缓存区
        byte[] buffer = new byte[1024];
        //获取Output的Stream流
        ServletOutputStream out = resp.getOutputStream();
        while((len = in.read(buffer))>0){
            out.write(buffer,0,len);
        }
        //关闭流
        out.close();
        in.close();
    }
}

配置servlet

<servlet>
    <servlet-name>download</servlet-name>
    <servlet-class>com.cai.servlet.DownLoadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>download</servlet-name>
    <url-pattern>/down</url-pattern>
  </servlet-mapping>

 

posted on 2020-11-25 21:40  Difcipo  阅读(67)  评论(0编辑  收藏  举报

导航