8.1文件下载

参考博客

前台构造超链接:

<a href="http://localhost:9898/blog/blog/Download?fileName=xxx.docx">download</a>

后台处理逻辑:将文件写到response的输出流

@WebServlet("/Download")
public class Download extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String fileName = req.getParameter("fileName");

        ServletContext servletContext = req.getServletContext();
        resp.setContentType(servletContext.getMimeType(fileName));
        resp.setHeader("Content-Disposition", "attachment;filename="+fileName);

//        String dir = servletContext.getRealPath("/WEB-INF/classes/files");
        String dir = "D:/logs/uploadFiles/";
        String fullFileNmame = dir + fileName;
        System.out.println("download file: " + fullFileNmame);

        FileInputStream fi = new FileInputStream(fullFileNmame);

        ServletOutputStream so = resp.getOutputStream();

        int len;
        byte[] buffer = new byte[4096];//4k
        while ((len = fi.read(buffer)) != -1){
            so.write(buffer, 0, len);
        }


        so.flush();
        fi.close();
        so.close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

@WebServlet("/Download")
public class Download extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String fileName = req.getParameter("fileName");
        ServletContext servletContext = req.getServletContext();
        resp.setContentType(servletContext.getMimeType(fileName));
        resp.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));

//        String dir = servletContext.getRealPath("/WEB-INF/classes/files");
        String dir = "D:/logs/uploadFiles/";
        String fullFileNmame = dir + fileName;
        System.out.println("download file: " + fullFileNmame);

        try(FileInputStream fi = new FileInputStream(fullFileNmame);
            BufferedInputStream bi = new BufferedInputStream(fi);
            //自带缓冲区
            ServletOutputStream so = resp.getOutputStream()){

            int len;
            while ((len = bi.read()) != -1){
                so.write(len);
            }

            so.flush();
        }
    }
}

IE因为编码问题解析request URL失败。