实现多个存储服务器上文件浏览器打包下载

关于本地文件zip打包返回给浏览器下载,这边有个很好的例子读取本地文件打包返回给浏览器下载,基本能解决的相关问题。而最近因为项目原因,打包返回给浏览器下载的是存储在fdfs上文件,然后对此代码修改了下,解决了项目需求。所以就记录下,以便后续使用。

public void getAllFile(HttpServletResponse response,String callId) throws IOException{
        String zipName = "file.zip";
        //获取符合下载条件的实体列表,根据自己的需求定义
        List<FileBean> fileList = getFileList(callId);
        response.setContentType("APPLICATION/OCTET-STREAM");  
        response.setHeader("Content-Disposition","attachment; filename="+zipName);
        ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
        try {
            for(FileBean fileBean: fileList){
                if(null==fileBean){
                    continue;
                }

          //只改变了以下这个方法即可
            ZipUtils.doZip(fileBean.getFilePath(),fileBean.getFileName(), out);
                response.flushBuffer();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            out.close();
        }
    }

这边就ZipUtils工具类里的doZip()方法略微改变了下,如下:

public static void doZip(String inFile, String entryName,ZipOutputStream out)
            throws IOException {
        URL urlfile = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
//      String entryName = null;
//      if (!"".equals(dir)) {
//          entryName = dir + "/" + inFile.getName();
//      } else {
//          entryName = inFile.getName();
//      }
        ZipEntry entry = new ZipEntry(entryName);
        out.putNextEntry(entry);

        int len = 0;
        byte[] buffer = new byte[1024];
//      FileInputStream fis = new FileInputStream(inFile);
//      BufferedOutputStream bos = null;
        urlfile = new URL(inFile);
        httpUrl = (HttpURLConnection) urlfile.openConnection();
        httpUrl.connect();
        try {
            bis = new BufferedInputStream(httpUrl.getInputStream());
        } catch (FileNotFoundException f1) {
            return;
        }
        while ((len = bis.read(buffer)) > 0) {
            out.write(buffer, 0, len);
            out.flush();
        }
        out.closeEntry();
        bis.close();
        httpUrl.disconnect();
    }

即可正确实现多文件打包下载。当然,与此类同,其他相似的存储系统文件打包下载,也可如此操作,进行打包下载,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值