springboot项目中将服务器文件打包zip格式下载功能

 把服务器存储的上传文件,批量下载到本地.参考网上资料,实现了服务器文件打包成zip压缩文件然后下载到本地. 代码实现如下:
1、pom.xml中添加FileUtils和IOUtils工具类依赖:

    commons-io
    commons-io
    2.2

2、在服务器端创建一个临时zip格式文件
3、将服务器所有文件输入到新建临时zip文压中
4、将zip文件下载到本地
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
Sbcpolicylabel sbcpolicylabel = sbCommonService.findDowInfoByPolicy(policyNo);
ArrayList iconNameList = new ArrayList();//返回文件名数组

String zipName = UUID.randomUUID().toString()+".zip";
String outFilePath = request.getSession().getServletContext().getRealPath("/")+"upload";
File fileZip = new File(outFilePath+zipName);
if("filecomplaintflag".equals(flag)){
    try {
        if ((sbcpolicylabel.getFilecomplaint() != null || !"".equals(sbcpolicylabel.getFilecomplaint()) || !"null".equals(sbcpolicylabel.getFilecomplaint()))) {

            String filecomplaintpath = sbcpolicylabel.getFilecomplaint();
            List fileList = FileUtil.getFiles(filecomplaintpath);
            FileOutputStream outStream = new FileOutputStream(fileZip);
            ZipOutputStream toClient = new ZipOutputStream(outStream);
            IOtools.zipFile(fileList,toClient);
            toClient.close();
            outStream.close();
            IOtools.downloadFile(fileZip,response,true);
            return null;

        //单个文件下载
        /**
            for (int i = 0; i < fileList.size(); i++) {
                String curpath = fileList.get(i).getPath();//获取文件路径
                iconNameList.add(curpath.substring(curpath.lastIndexOf("\\") + 1));//将文件名加入数组

                String fileName = new String(filecomplaintpath.getBytes("UTF-8"),"iso8859-1");
                headers.setContentDispositionFormData("attachment", fileName);
                return new ResponseEntity[]>(FileUtils.readFileToByteArray(new File(filecomplaintpath)),
                        headers, HttpStatus.OK);
            }
         **/
        }
    }catch(Exception e){
        log.info("系统异常,请从新录入!");
        e.printStackTrace();
    }
IOtools工具类
public class IOtools {

    /**
    * 将服务器文件存到压缩包中
    */
    public static void zipFile(List files, ZipOutputStream outputStream) throws IOException, ServletException {
        try {
            int size = files.size();
            // 压缩列表中的文件
            for (int i = 0; i < size; i++) {
                File file = (File) files.get(i);
                zipFile(file, outputStream);
            }
        } catch (IOException e) {
            throw e;
        }
    }
    public static void zipFile(File inputFile, ZipOutputStream outputstream) throws IOException, ServletException {
        try {
            if (inputFile.exists()) {
                if (inputFile.isFile()) {
                    FileInputStream inStream = new FileInputStream(inputFile);
                    BufferedInputStream bInStream = new BufferedInputStream(inStream);
                    ZipEntry entry = new ZipEntry(inputFile.getName());
                    outputstream.putNextEntry(entry);

                    final int MAX_BYTE = 10 * 1024 * 1024; // 最大的流为10M
                    long streamTotal = 0; // 接受流的容量
                    int streamNum = 0; // 流需要分开的数量
                    int leaveByte = 0; // 文件剩下的字符数
                    byte[] inOutbyte; // byte数组接受文件的数据

                    streamTotal = bInStream.available(); // 通过available方法取得流的最大字符数
                    streamNum = (int) Math.floor(streamTotal / MAX_BYTE); // 取得流文件需要分开的数量
                    leaveByte = (int) streamTotal % MAX_BYTE; // 分开文件之后,剩余的数量

                    if (streamNum > 0) {
                        for (int j = 0; j < streamNum; ++j) {
                            inOutbyte = new byte[MAX_BYTE];
                            // 读入流,保存在byte数组
                            bInStream.read(inOutbyte, 0, MAX_BYTE);
                            outputstream.write(inOutbyte, 0, MAX_BYTE); // 写出流
                        }
                    }
                    // 写出剩下的流数据
                    inOutbyte = new byte[leaveByte];
                    bInStream.read(inOutbyte, 0, leaveByte);
                    outputstream.write(inOutbyte);
                    outputstream.closeEntry(); // Closes the current ZIP entry
                    // and positions the stream for
                    // writing the next entry
                    bInStream.close(); // 关闭
                    inStream.close();
                }
            } else {
                throw new ServletException("文件不存在!");
            }
        } catch (IOException e) {
            throw e;
        }
    }

    public static void downloadFile(File file, HttpServletResponse response, boolean isDelete) {
        try {
            // 以流的形式下载文件。
            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("UTF-8"),"ISO-8859-1"));
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
            if(isDelete)
            {
                file.delete();        //是否将生成的服务器端文件删除
            }
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}
文件夹下文件和目录递归遍历方法
public static ArrayList getFiles(String path) throws Exception {
    //目标集合fileList
    ArrayList fileList = new ArrayList();
    File file = new File(path);
    if(file.isDirectory()){
        File []files = file.listFiles();
        for(File fileIndex:files){
            //如果这个文件是目录,则进行递归搜索
            if(fileIndex.isDirectory()){
                getFiles(fileIndex.getPath());
            }else {
             //如果文件是普通文件,则将文件句柄放入集合中
                fileList.add(fileIndex);
            }
        }
    }
    return fileList;
}


你可能感兴趣的:(Spring,Boot)