指定目录下载文件并转为压缩包下载到指定目录

该篇文章详细描述了一个名为DownloadAndUploadController的控制器,使用SpringMVC的@RestController和@RequestMapping处理HTTP请求。它实现了一个/downloadBatch方法,接收文件下载请求,检查文件列表,如果存在则进行文件的批量下载并压缩到指定路径。
摘要由CSDN通过智能技术生成

@RestController
@RequestMapping(“/file”)
@Slf4j
public class DownloadAndUploadController {

@PostMapping("/downloadBatch")
public void downloadBatch(HttpServletRequest request, HttpServletResponse response, @RequestBody FileDownloadDTO fileDownloadDTO) {

    List<String> fileUrl = fileDownloadDTO.getFileUrl();
    if (CollectionUtils.isEmpty(fileUrl)) {
        System.out.println("文件列表空,无需下载");
        return;
    }
    String[] path = fileUrl.toArray(new String[fileUrl.size()]);
    //需要压缩的文件,包括文件地址和文件名
    String desPath = fileDownloadDTO.getDesPath();
    Path path1 = Paths.get(fileDownloadDTO.getDesPath());
    try {
        if (!Files.exists(path1)) {
            //路径不存在,创建它
            Files.createDirectories(path1.getParent());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    File zipFile = new File(desPath);
    ZipOutputStream zipStream = null;
    FileInputStream zipSource = null;
    BufferedInputStream bufferStream = null;

    try {
        //构造最终压缩包的输出流
        zipStream = new ZipOutputStream(new FileOutputStream(zipFile));
        for (int i = 0; i < path.length; i++) {
            File file = new File(path[i]);
            zipSource = new FileInputStream(file);
            ZipEntry zipEntry = new ZipEntry(file.getName());
            zipStream.putNextEntry(zipEntry);

            bufferStream = new BufferedInputStream(zipSource, 1024 * 10);
            int read = 0;

            //创建读写缓冲区
            byte[] buf = new byte[1024 * 10];
            while ((read = bufferStream.read(buf, 0, 1024 * 10)) != -1) {
                zipStream.write(buf, 0, read);
            }
        }
        System.out.println("文件下载到指定位置" + desPath);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            //关闭流
            if (null != bufferStream) {
                bufferStream.close();
            }
            if (null != zipSource) {
                zipSource.close();
            }
            if (null != zipStream) {
                zipStream.close();
            }
            System.out.println("流关闭成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

}

  • 11
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值