java根据路径批量下载图片为zip

前台代码

//头工具栏事件
            table.on('toolbar(test)', function(obj){
                var checkStatus = table.checkStatus(obj.config.id);
                var requestNos = [];
                switch(obj.event){
                    case 'requestSeeInto':
                        var data = checkStatus.data;
                    //    console.log(data);
                        for(var i=0;i<data.length;i++){
                            requestNos.push(data[i].ID);
                        }
                };
                var requestData = requestNos.join(",");
                if(requestData==null||requestData==""){
                    layer.alert("请勾选文件序号");
                    return;
                }
              //  console.log(requestData);

                window.open("/dz_exchange/api/license/batchDownLoad?path="+encodeURI(requestData))
            });

后台代码:

 @RequestMapping(value = "/batchDownLoad", method = RequestMethod.GET)
    public void batchDownLoad() throws Exception {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpServletResponse response = requestAttributes.getResponse();
        //这里是前台传的以逗号分隔的id 根据id去分别查询对应的path
        String path = request.getParameter("path");
        String[] split = path.split(",");
        //响应头的设置
        response.reset();
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.addHeader("Access-Control-Allow-Origin", "*");//解决跨域
        //设置压缩包的名字
        Date date = new Date();
        String billname = "附件包-" + date.getTime();
        String downloadName = billname + ".zip";
        //返回客户端浏览器的版本号、类型
        String agent = request.getHeader("USER-AGENT");
        try {
            //针对IE或者以IE为内核的浏览器:
            if (agent.contains("MSIE") || agent.contains("Trident")) {
                downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");
            } else {
                //非IE浏览器的处理:
                downloadName = new String(downloadName.getBytes("UTF-8"), "ISO-8859-1");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\"");

        //设置压缩流:直接写入response,实现边压缩边下载
        ZipOutputStream zipos = null;
        try {
            zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
            zipos.setMethod(ZipOutputStream.DEFLATED); //设置压缩方法
        } catch (Exception e) {
            e.printStackTrace();
        }
        //循环将文件写入压缩流
        DataOutputStream os = null;

        //查询数据库获取文件信息

        //遍历文件信息(主要获取文件名/文件路径等)
        for (int i = 0; i < split.length; i++) {
            //根据id数据库获取
            // 文件路径
            String filePath = addLicenseDao.queryFilepath(split[i]);
            System.out.println("filePath===" + filePath);
            File file = new File(filePath);
            if (!file.exists()) {
                throw new Exception();
            } else {
                try {
                    //添加ZipEntry,并ZipEntry中写入文件流
                    String fileName = file.getName();//.substring(0,authAttachmentDetail.getFileName().indexOf("."));
                    zipos.putNextEntry(new ZipEntry(fileName));
                    os = new DataOutputStream(zipos);
                    InputStream is = new FileInputStream(file);
                    byte[] b = new byte[100];
                    int length = 0;
                    while ((length = is.read(b)) != -1) {
                        os.write(b, 0, length);
                    }
                    is.close();
                    zipos.closeEntry();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //关闭流
        try {
            os.flush();
            os.close();
            zipos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Java中实现批量下载并将文件打包为ZIP格式,可以使用java.util.zip包提供的类和方法。以下是一个简单的实现示例: 首先,需要准备一个文件列表,包含要下载的文件的路径。可以通过手动指定路径,或者通过程序动态获取,具体根据需求而定。 接下来,需要使用java.util.zip包中的ZipOutputStream类和FileInputStream类来实现文件的打包。可以创建一个空的ZipOutputStream对象,并使用FileInputStream读取每个文件,然后将其添加到ZipOutputStream中。最后,关闭ZipOutputStream。 同时,还需要使用java.net包中的URLURLConnection类来进行文件的下载。可以为每个需要下载的文件创建一个URL对象,打开URLConnection连接并获取其输入流。然后,将输入流传递给FileOutputStream,使用java.io包中的FileOutputStream类将文件下载到本地。 以下是一个简单的示例代码: import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipDownloader { public static void main(String[] args) { List<String> fileList = getListOfFiles(); // 获取文件列表,具体根据需求实现 String zipFileName = "downloadedFiles.zip"; // 设定打包后的ZIP文件名 try { FileOutputStream fos = new FileOutputStream(zipFileName); ZipOutputStream zos = new ZipOutputStream(fos); for (String file : fileList) { URL url = new URL(file); URLConnection connection = url.openConnection(); InputStream is = connection.getInputStream(); zos.putNextEntry(new ZipEntry(file)); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { zos.write(buffer, 0, length); } is.close(); } zos.closeEntry(); zos.close(); System.out.println("文件下载并打包为ZIP完成。"); } catch (IOException e) { e.printStackTrace(); } } } 需要注意的是,该示例只是一个简单的实现,并没有处理异常情况,如文件不存在、网络连接失败等。在实际应用中,需要对这些异常进行适当的处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值