浏览器下载压缩包

浏览器下载压缩包

#需求如下
通过前台传入id数据库查询数据,写入临时文件,再将临时文件存入,压缩包,一起打包下载。
#代码如下

 /**
     * 下载授权压缩包
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(params = "downloadAuthorization")
    @ResponseBody
    public void downloadAuthorization(HttpServletRequest request, HttpServletResponse response, String id) throws Exception {
        KeysignatureEntity t = keysignatureService.get(KeysignatureEntity.class, id);
        String fileName = URLEncoder.encode(t.getUserName() + ".zip", StandardCharsets.UTF_8.toString());
        response.setContentType("application/zip");
        // 下面设置方法可以解决文件名乱码问题
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"; filename*=utf-8''" + fileName);
        List<File> files = new ArrayList<File>();

        //公钥
        File publicKeyFile = new File("publicKey.txt");
        FileWriter publicKeyWriter = new FileWriter(publicKeyFile);
        publicKeyWriter.write(t.getPublicKey());
        files.add(publicKeyFile);
        publicKeyWriter.close();

        //密文
        File cipherFile = new File("cipher.txt");
        FileWriter cipherWriter = new FileWriter(cipherFile);
        cipherWriter.write(t.getCipher());
        files.add(cipherFile);
        cipherWriter.close();

        //说明
        File instructionsFile = new File("instructions.txt");
        FileWriter instructionsWriter = new FileWriter(instructionsFile);
        instructionsWriter.write("用户名称:" + t.getUserName() + ";");
        instructionsWriter.write("截止时间:" + t.getByTime() + ";");
        instructionsWriter.write("授权模块:" + t.getAuthorizationModule() + ";");
        files.add(instructionsFile);
        instructionsWriter.close();


        ZipOutputStream out = null;
        try {
            byte[] buffer = new byte[1024];
            out = new ZipOutputStream(response.getOutputStream());
            for (File file : files) {
                FileInputStream fis = new FileInputStream(file);
                out.putNextEntry(new ZipEntry(file.getName()));
                int len;
                //读入需要下载的文件的内容,打包到zip文件
                while ((len = fis.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                out.flush();
                out.closeEntry();
                fis.close();
            }
            //输出到浏览器
            OutputStream ou = out;
            ou.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

效果如下

QQ20200427-161935@2x