Using a servlet, how do you download multiple files from a database and zip them for client download

萝らか妹 提交于 2019-12-05 08:45:06

In case this can be helpful to anyone else, I found the answer to the problem. The code posted above actually works perfectly for downloading multiple files from a database and creating a zip file for the client to download. The problem was that I was calling the servlet via ajax, and apparently you can't download files via an ajax call. So I changed my jsp page to call the servlet via submitting a form, and then the download came through to the browser perfectly.

First create a zip file which contains all the zip files.

Use ServletOutputStream instead of ZipOutputStream.

Then use the below code

protected void doGet(final HttpServletRequest request, final HttpServletResponse response) {
        final String filename = "/usr/local/FileName" + ".zip";

        BufferedInputStream buf = null;
        ServletOutputStream myOut = null;

        try {
            myOut = response.getOutputStream();

            File myfile = new File(filename);

            if (myfile.exists()) {
                //myfile.createNewFile();
                //set response headers
                response.setHeader("Cache-Control", "max-age=60");
                response.setHeader("Cache-Control", "must-revalidate");
                response.setContentType("application/zip");

                response.addHeader("Content-Disposition", "attachment; filename=" + filename);

                response.setContentLength((int) myfile.length());

                FileInputStream input = new FileInputStream(myfile);
                buf = new BufferedInputStream(input);
                int readBytes = 0;

                //read from the file; write to the ServletOutputStream
                while ((readBytes = buf.read()) != -1) {
                    myOut.write(readBytes);
                }
            }

        } catch (Exception exp) {
        } finally {
            //close the input/output streams
            if (myOut != null) {
                try {
                    myOut.close();
                } catch (IOException ex) {
                }
            }
            if (buf != null) {
                try {
                    buf.close();
                } catch (IOException ex) {
                }
            }

        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!