java 批量下载文件(开发笔记)

本文介绍了一种在Java中实现的文献批量下载及压缩的方法。该方法能够根据用户选择,下载单个或多个文献,当下载多个文献时,将它们压缩成一个.zip文件。代码利用了Spring框架的ResponseEntity与InputStreamResource,以及MongoDB的GridFS进行文件存储与检索。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:

 下载文件,选择单个文档则下载单个文档,选择多个文档则讲多个文档压缩进一个压缩文件。

 

    public ResponseEntity<InputStreamResource> downloadFiles(String literIds,String type) throws YMLibWebApplicationException {
        Assert.notNull(literIds, "未指定要下载的文献");
        if(null==type){
            type="";
        }
        String[] ids = literIds.split(",");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        QFullTextLibrary qfullTextLibrary = QFullTextLibrary.fullTextLibrary;
        Predicate predicate = qfullTextLibrary.id.in(ids);
        Iterable<FullTextLibrary> iter = fullTextLibraryRepository.findAll(predicate);
        int total = 0;
        String fileName = "";
        Collection<String> fileIds = new ArrayList<String>();
    
        for (FullTextLibrary one : iter) {
            
            String fileId = one.getFileId();
            if (fileId != null && !fileId.equals("")) {
                            
                fileIds.add(fileId);
                
                total++;
            }
            
            
        }
        if (total > 1) {
            fileName = DateUtils.date2String("yyyymmdd") + ".zip";
        }
        headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName));
        long length = 0L;
 
        Criteria cr = Criteria.where("_id").in(fileIds);
        Query query = new Query(cr);
        List<GridFSDBFile> files = gridFsOps.find(query);
        if (!files.isEmpty()) {
            if (files.size() == 1) {
                GridFSDBFile file = files.get(0);
                length = file.getLength();
                return ResponseEntity.ok().contentLength(length).contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .cacheControl(CacheControl.maxAge(3600, TimeUnit.SECONDS)).headers(headers)
                        .body(new InputStreamResource(file.getInputStream()));
 
            } else {
                    long statr_time=System.currentTimeMillis();
                try {
                    String zipfilePath = zipFilePath + fileName;
                    FileOutputStream outputStream = new FileOutputStream(zipfilePath);
                    ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(outputStream));
                    // zipOut.putNextEntry(new ZipEntry("/"));
                    for (GridFSDBFile file : files) {
                        length += file.getLength();
                        InputStream in = file.getInputStream();
                        String file_id=file.getId().toString();
                        zipOut.putNextEntry(new ZipEntry(file.getName()));
                        int j = 0;
                        byte[] buffer = new byte[1024*1024];
                        while ((j = in.read(buffer)) > 0) {
                            zipOut.write(buffer, 0, j);
                        }
                        // 关闭输入流
                        in.close();
                    }
                    zipOut.closeEntry();
                    zipOut.flush();
                    zipOut.close();
                    // 文件压缩成功
                    FileInputStream inputStream = new FileInputStream(zipfilePath);
                    
                    long end_time=System.currentTimeMillis();
                    System.out.println(end_time-statr_time);
                    return ResponseEntity.ok().contentLength(length).contentType(MediaType.APPLICATION_OCTET_STREAM)
                            .headers(headers)
                            .body(new InputStreamResource(inputStream));
 
                } catch (Exception e) {
                    log.error("压缩文件出错", e);
                }
            }
        }
 
        return null;
 
    }
 

文件通过mongoid 去mongofs里面拿,拿出来后判断文件的个数,多个文件则进行压缩。代码如上图。
DEMO下载地址:https://dwz.cn/Jw3z6fVq

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值