java implements file packaging compression and output to browser for download

  • 2021-12-12 04:33:08
  • OfStack

The file is packaged, compressed and output to the browser for download

java batch download file packaging compression tool class, output to the browser download, can be renamed.

1. Tool class:

Reference: document LIst;; The name after packing; Respond to Browser


/**
     *  Function : Compress multiple files and output the compressed zip File stream 
     *
     * @param srcfile List of source files 
     * @param zipFileName File name after compression 
     * @param response:           Http Response 
     */
    public void zipFiles(List<File> srcfile, String zipFileName, HttpServletResponse response) throws IOException {
        byte[] buf = new byte[1024];
        //  Get the output stream 
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileInputStream in = null;
        ZipOutputStream out = null;
        try {
            response.reset(); //  Highlight the key points 
            //  Different types of files correspond to different MIME Type 
            response.setContentType("application/x-msdownload");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + zipFileName + ".zip");
 
            // ZipOutputStream Class: Complete the compression of files or folders 
            out = new ZipOutputStream(bos);
            for (int i = 0; i < srcfile.size(); i++) {
                in = new FileInputStream(srcfile.get(i));
                //  Give individual names to files in the list 
                out.putNextEntry(new ZipEntry(srcfile.get(i).getName()));
                int len = -1;
                while ((len = in.read(buf)) != -1) {
                    out.write(buf, 0, len);
                }
            }
            out.close();
            bos.close();
            log.info(" Compression complete .");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) in.close();
            if (out != null) out.close();
        }
    }

2. Call


zipFiles(files, zipName, response);

Generate zip file and export it to browser

Summary 1, about Java download zip file and export method, browser export.


       String downloadName = " Download file name .zip";
        downloadName = BrowserCharCodeUtils.browserCharCodeFun(request, downloadName);// Solution to the problem of garbled download file name 
        
        // Package and download files 
        try {
            OutputStream out = response.getOutputStream();
            byte[] data = createZip("/fileStorage/download");// Server storage address 
            response.reset();
            response.setHeader("Content-Disposition","attachment;fileName="+downloadName);
            response.addHeader("Content-Length", ""+data.length);
            response.setContentType("application/octet-stream;charset=UTF-8");
            IOUtils.write(data, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

Get the download zip file stream


public byte[] createZip(String srcSource) throws Exception{
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        // Package the object file into zip Export 
        File file = new File(srcSource); 
        a(zip,file,"");
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

public void a(ZipOutputStream zip, File file, String dir) throws Exception {
            // If the current folder is a folder, proceed to 1 Step processing 
            if (file.isDirectory()) {
                // Get file list information 
                File[] files = file.listFiles();
                // Add a folder to the following 1 Level packaging directory 
                zip.putNextEntry(new ZipEntry(dir + "/"));
                dir = dir.length() == 0 ? "" : dir + "/";
                // Loop to pack the files in the folder 
                for (int i = 0; i < files.length; i++) {
                    a(zip, files[i], dir + files[i].getName());         // Recursive processing 
                }
            } else {   // The current one is a file, which is packaged and processed 
                // File input stream 
               BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
               ZipEntry entry = new ZipEntry(dir);
               zip.putNextEntry(entry);
               zip.write(FileUtils.readFileToByteArray(file));
               IOUtils.closeQuietly(bis);
               zip.flush();
               zip.closeEntry();
            }
    }

Related articles: