java实现打包下载

背景:项目中下载功能单个文件正常下载多个文件或者包含文件夹打压缩包下载

上代码

controller

@RestController
@RequestMapping("/file")
public class FileController {


    
    @RequestMapping(value = "/downloadFilePack", method = RequestMethod.GET)
    public void downloadFilePack(String username, String wellName,HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isBlank(username) ) {
            throw new ResultMapException("参数为空");
        }
        FileUtil.downloadFilePack(username,wellName, request, response);

    }


}

FileUtile工具类

package com.yxsd.stratum.resource.utils;

import com.cloud.framework.util.DateUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.result.ResultMapException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileUtil {

   
   
    public static void downloadFilePack(String username, String wellName, HttpServletRequest request, HttpServletResponse response) {
        Path path =null;
        //根据参数拼的下载路径 可根据业务自己改造
        if(StringUtils.isBlank(wellName)){
          path = Paths.get(ConstantUtils.SCRIPT_BASE_DATA_PATH,username,ConstantUtils.SCRIPT_BASE_DATA_PATH_GROUP_ACCURACY_PATH);
         }else {
            wellName= wellName+".xlsx";
            path = Paths.get(ConstantUtils.SCRIPT_BASE_DATA_PATH,username,ConstantUtils.SCRIPT_BASE_DATA_PATH_GROUP_ACCURACY_PATH,wellName);
         }
        if(Files.notExists(path)){
            throw new ResultMapException("文件不存在");
        }
        List<String> list = new ArrayList<String>();
        if(Files.isDirectory(path)){
            try {
                Stream<Path> paths = Files.list(path);
                paths.forEach(p -> list.add(p.toString()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            list.add(path.toString());
        }

        File file = new File(list.get(0));
        // 如果下载多个文件或下载文件夹,将文件打成压缩包进行下载
        if (list.size() > 1 || file.isDirectory()) {
            String fileZipName = DateUtils.getInstance().dateFormat(new Date()) + ".zip";
            String fileZipPath = ConstantUtils.PDF_TEMP + File.separator + fileZipName;
            zipFiles(list, fileZipPath);
            downloadF(request, response, download(fileZipPath), fileZipName);
            delete(fileZipPath);
        } else {
            // 单个文件直接下载
            downloadF(request, response, download(file.getPath()), file.getName());
        }

    }


    public static void downloadF(HttpServletRequest request, HttpServletResponse response, InputStream inputStream, String fileName) {
        OutputStream os = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //通过response获取的输出流,作为服务端向客户端浏览器输出内容的通道
            os = response.getOutputStream();
            // 为了提高效率使用缓冲区流
            bis = new BufferedInputStream(inputStream);
            bos = new BufferedOutputStream(os);
            // 处理下载文件名的乱码问题(根据浏览器的不同进行处理)
            if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
                fileName = new String(fileName.getBytes("GB2312"), "ISO-8859-1");
            } else {
                // 对文件名进行编码处理中文问题
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");// 处理中文文件名的问题
                fileName = new String(fileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题
            }
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-msdownload");// 不同类型的文件对应不同的MIME类型
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            int bytesRead = 0;
            byte[] buffer = new byte[4096];
            while ((bytesRead = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
                bos.flush();
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex.getMessage());
        } finally {
            try {
                if (null != bis) {
                    bis.close();
                    bis = null;
                }
                if (null != bos) {
                    bos.close();
                    bos = null;
                }
                if (null != os) {
                    os.close();
                    os = null;
                }
            } catch (Exception ex) {
                throw new RuntimeException(ex.getMessage());
            }
        }
    }


    public static void zipFiles(List<String> srcfiles, String zipPath) {
        File fileParent = new File(zipPath);
        if (!fileParent.getParentFile().exists() && !fileParent.isDirectory()) {
            fileParent.getParentFile().mkdirs();
        }

        byte[] buf = new byte[4096];
        ZipOutputStream out = null;
        try {
            // 创建zip输出流
            out = new ZipOutputStream(new FileOutputStream(fileParent));
            // 循环将源文件列表添加到zip文件中
            for (int i = 0; i < srcfiles.size(); i++) {
                File file = new File(srcfiles.get(i));
                FileInputStream in = new FileInputStream(file);
                String fileName = file.getName();
                // 将文件名作为zip的Entry存入zip文件中
                out.putNextEntry(new ZipEntry(fileName));
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
    }


    public static InputStream download(String fromPath) {
        FileInputStream inputStream = null;
        try {
            File file = new File(fromPath);
            if (file.exists()) {
                inputStream = new FileInputStream(file);
            }
        } catch (Exception var4) {
            var4.printStackTrace();
        }
        return inputStream;
    }

    public static Boolean delete(String path) {
        Boolean result = false;
        try {
            File remoteFile = new File(path);
            if (!remoteFile.exists()) {
                return false;
            }
            if (remoteFile.isFile()) {
                result = remoteFile.delete();
            } else {
                FileUtils.deleteDirectory(remoteFile);
                result = true;
            }
        } catch (Exception var4) {
            var4.printStackTrace();
            result = false;
        }

        return result;
    }

}

测试  页面请求

http://127.0.0.1:9091/file/downloadFilePack?username=%22test%22&wellName=%2211%22

 

解压看是否乱码 正常

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值