批量下载文件,将文件打包成压缩文件

批量压缩文件

 public static byte[] zipFiles(List<File> listfiles) throws IOException {
        byte[] buf = new byte[1024];
        ByteArrayOutputStream outPut = new ByteArrayOutputStream();
        ZipOutputStream out = new ZipOutputStream(outPut);
        List<String> nameList = new ArrayList<>();
        for (File file : listfiles) {
            InputStream input = new ByteArrayInputStream(file.getContent());

            if (nameList.size() > 0 && CommonUtil.existsStrList(nameList, file.getFileName())) {
                out.putNextEntry(new ZipEntry(CommonUtil.returnChangeFileName(file.getFileName(), nameList.size())));
            } else {
                nameList.add(file.getFileName());
                out.putNextEntry(new ZipEntry(file.getFileName()));
            }

            int len;
            while ((len = input.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.closeEntry();
            input.close();
        }
        out.close();
        return outPut.toByteArray();
    }

输出压缩后的文件

  public Message downloadAll(Message msg) throws IOException {
        Message m = new Message();

        FileDto dto = getParamBean(msg, FileDto.class);
        // idList 为file的idlist
        List<File> list = fileService.getFileList(dto.getFileIdList());
        byte[] byteInfo = null;
        if (list != null) {
            byteInfo = ZIPUtils.zipFiles(list);
        }
        String fileName = new String((CommonUtil.uuid() + ".zip").getBytes("UTF-8"), "ISO-8859-1");
        m.setBody(byteInfo);
        m.setStatus(HttpStatus.HTTP_OK);
        m.setHead(Message.CONTENT_LENGTH, byteInfo.length + "");
        m.setHead("Content-Disposition", "attachment;filename=\"" + fileName
                + "\"");
        return m;
    }

猜你喜欢

转载自blog.csdn.net/weixin_42228950/article/details/85778658