前后端分离项目后端向前端返回压缩包的方法实现java版

2021/9/23 22:40:51

本文主要是介绍前后端分离项目后端向前端返回压缩包的方法实现java版,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

最近公司的项目是让前端有让用户下载zip压缩包(里面都是图片,图片是保存在ftp上的)的任务,经过调研,将最终方案复制在下面:

  //zip文件的下载
    @GetMapping("/zip/{imagePath}")
    @ResponseBody
    public void zip(HttpServletResponse response, @PathVariable(value = "imagePath", required = false) String imagePathList) throws IOException {
        String[] imagePaths = imagePathList.split(CCPCommon.CCP_SEPARATOR);
        //设置返回响应头
        response.reset();
        // 自动判断下载文件类型
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("picture.zip", "UTF-8"));

        FTPClient ftpClient;
        ftpClient = FtpUtil.getFTPClient("xxx", "xxx", "xxx", 21);
        // 中文支持
        ftpClient.setControlEncoding("UTF-8");
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();
        ftpClient.changeWorkingDirectory("ftp://xxx");
        ZipOutputStream zos = null;
        OutputStream os = response.getOutputStream();
        try {
            zos = new ZipOutputStream(os);
            InputStream ins = null;
            for (String imagePath : imagePaths) {
                if (imagePath == null || imagePath.equals("") || imagePath.equals("undefined")) {//如果书没有上传
                    continue;
                }
                ins = ftpClient.retrieveFileStream(new String(imagePath.getBytes("UTF-8"), "iso-8859-1"));
                if (ins != null) {
                    zos.putNextEntry(new ZipEntry(imagePath));
                    int len;
                    byte[] buff = new byte[1024];
                    while (-1 != (len = ins.read(buff, 0, buff.length))) {
                        zos.write(buff, 0, len);
                    }
                    zos.closeEntry();
                    ins.close();
                    ftpClient.completePendingCommand();//不让一个循环后ftpClient自动关闭
                }
            }
            zos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

这里很重要的操作:

  //设置返回响应头
        response.reset();
        // 自动判断下载文件类型
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("picture.zip", "UTF-8"));

一定要设置响应头部的type,并且可以给这个压缩包起一个名字。
还有就是ftp的一个细节:

 ftpClient.completePendingCommand();

如果不加这一行,ftp自动会关闭连接,一定要让它保持连接状态。



这篇关于前后端分离项目后端向前端返回压缩包的方法实现java版的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程