单文件下载, 多文件下载

1 篇文章 0 订阅

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.qjzh.common.exception.BusinessException;

@SuppressWarnings(value = "all")
public class DownloadFile {
	/**
	 * 单文件下载
	 * @param path
	 * @param fileName
	 * @param response
	 * @return
	 */
	public String oneFileDownload(String path, String fileName, HttpServletResponse response) {
		// 针对需求需要与需求沟通下载文件传递参数
		// 目前demo文件名是文件的hashCode值+后缀名的方式命名,可以默认该hashCode值为文件唯一id
		if (StringUtils.isBlank(fileName)) {
			return "文件名为空";
		}
		String filePath = path + File.separator + fileName;// 目前文件默认在该文件夹下,后续变动需修改
		File downloadFile = new File(filePath);
		if (downloadFile.exists()) {
			OutputStream out = null;
			FileInputStream fis = null;
			BufferedInputStream bis = null;
			try {
				if (downloadFile.isDirectory()) {
					return "路径错误仅指向文件夹";
				}
				out = response.getOutputStream();// 创建页面返回方式为输出流,弹出下载框
				fis = new FileInputStream(downloadFile);
				bis = new BufferedInputStream(fis);
				response.setContentType("application/pdf; charset=UTF-8");// 设置编码字符
				response.setHeader("Content-disposition", "attachment;filename=" + fileName);
				byte[] bt = new byte[2048];
				int size = 0;
				while ((size = bis.read(bt)) != -1) {
					out.write(bt, 0, size);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					// 关闭流
					out.flush();
					if (out != null) {
						out.close();
					}
					if (bis != null) {
						bis.close();
					}
					if (fis != null) {
						fis.close();
					}
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
			return "下载成功";
		} else {
			return "文件不存在!";
		}
	}

	/**
	 * 文件打包下载
	 * 
	 * @param sourceFilePath 下载文件目录
	 * @param destinFilePath 文件打包目录
	 * @param fileName       文件名称 (不用带zip)
	 * @param deleteSource   压缩后是否删除源文件
	 * @param response
	 * @throws IOException
	 * @throws BusinessException
	 */
	public void zipDownload(String sourceFilePath, String destinFilePath, String fileName, boolean deleteSource,
			HttpServletResponse response) throws IOException, BusinessException {
		//将文件打包成zip
		fileName = FileUtil.zipFiles(sourceFilePath, destinFilePath, fileName, deleteSource);
		File file = new File(destinFilePath + File.separator + fileName);

		response.setHeader("Content-disposition", "attachment;filename=" + fileName);
		if (file.exists()) {
			FileInputStream fis = null;
			BufferedInputStream bis = null;
			OutputStream out = response.getOutputStream();
			try {
				fis = new FileInputStream(file);
				bis = new BufferedInputStream(fis);
				byte[] bufs = new byte[1024 * 10];
				int read = 0;
				while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
					out.write(bufs, 0, read);
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
				if (bis != null) {
					bis.close();
				}
				if (out != null) {
					out.close();
				}
				File zipFile = new File(destinFilePath + File.separator + fileName);
				if (zipFile.exists()) {
					zipFile.delete();
				}
				if(deleteSource) {
					FileUtil.deleteDirectory(new File(sourceFilePath));
            	}
			}
		} else {
			throw new BusinessException("下载失败");
		}
	}

	/**
	 * 下载一个文件夹下的多个文件
	 * @param subFile  文件夹下文件的集合
	 * @param root     文件夹的路径
	 * @param zipBasePath  打包的路径
	 * @param fileName		文件名称(不带zip)
	 * @param response
	 * @return
	 */
	public String zipDownloadRelativePath(List<File> subFile, String root, String zipBasePath, String fileName, HttpServletResponse response) {
		String msg = "";// 下载提示信息
		Vector<File> fileVector = new Vector<File>();// 定义容器装载文件
		// 判断文件性质并取文件
		for (int i = 0; i < subFile.size(); i++) {
			File f = subFile.get(i);
			if (!f.isDirectory()) {// 不是文件夹并且不为空
				fileVector.add(f);// 装载文件
			} else {// 是文件夹,再次递归遍历文件夹里面的文件
				File[] files = f.listFiles();
				Vector v = FileUtil.getPathAllFiles(f, new Vector<File>());
				fileVector.addAll(v);// 把迭代的文件装到容器中
			}
		}
		
		// 设置文件下载名称
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		fileName = fileName + ".zip";
		response.setHeader("Content-disposition", "attachment;filename=" + fileName);// 如果有中文需要转码
		// 定义相关流
		// 用于浏览器下载响应
		OutputStream out = null;
		// 用于读压缩好的文件
		BufferedInputStream bis = null;// 用缓存性能会好一些
		// 用于压缩文件
		ZipOutputStream zos = null;
		
		File zipBaseFile = new File(zipBasePath);
		if(!zipBaseFile.exists()) {
			zipBaseFile.mkdirs();
		} 
		
		String zipFilePath = zipBasePath + File.separator + fileName;
		
		File zipFile = new File(zipFilePath);
		
		try {
			if (!zipFile.exists()) {// 不存在创建一个新的
				zipFile.createNewFile();
			}
			out = response.getOutputStream();
			// 创建文件输出流
			zos = new ZipOutputStream(new FileOutputStream(zipFile));
			// 循环文件,一个一个按顺序压缩
			for (int i = 0; i < fileVector.size(); i++) {
				System.out.println(fileVector.get(i).getName() + "大小为:" + fileVector.get(i).length());
				FileUtil.zipFileFun(fileVector.get(i), root, zos);
			}
			// 压缩完成以后必须要在此处执行关闭 否则下载文件会有问题
			if (zos != null) {
				zos.closeEntry();
				zos.close();
				zos = null;
			}
			byte[] bt = new byte[10 * 1024];
			int size = 0;
			bis = new BufferedInputStream(new FileInputStream(zipFilePath), 10 * 1024);
			while ((size = bis.read(bt, 0, 10 * 1024)) != -1) {// 没有读完
				out.write(bt, 0, size);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {// 关闭相关流
			try {
				// 避免出异常时无法关闭
				if (zos != null) {
					zos.closeEntry();
					zos.close();
				}

				if (bis != null) {
					bis.close();
				}

				if (out != null) {
					out.close();
				}
				if (zipFile.exists()) {
					zipFile.delete();// 删除
				}
			} catch (Exception e2) {
				System.out.println("流关闭出错!");
			}

		}
		return "下载成功";
	}
	
	/**
	 * 下载指定文件夹下的所有文件,支持树型结构
	 * 
	 * @param root           文件路径
	 * @param destinFilePath 存放zip的文件夹
	 * @param response
	 * @return
	 */
	public String zipDownloadRelativePath(String root, String zipBasePath, String fileName, HttpServletResponse response) {
		String msg = "";// 下载提示信息
		Vector<File> fileVector = new Vector<File>();// 定义容器装载文件
		File file = new File(root);
		File[] subFile = file.listFiles();
		// 判断文件性质并取文件
		for (int i = 0; i < subFile.length; i++) {
			if (!subFile[i].isDirectory()) {// 不是文件夹并且不为空
				fileVector.add(subFile[i]);// 装载文件
			} else {// 是文件夹,再次递归遍历文件夹里面的文件
				File[] files = subFile[i].listFiles();
				Vector v = FileUtil.getPathAllFiles(subFile[i], new Vector<File>());
				fileVector.addAll(v);// 把迭代的文件装到容器中
			}
		}
		// 设置文件下载名称
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		fileName = fileName + ".zip";
		response.setHeader("Content-disposition", "attachment;filename=" + fileName);// 如果有中文需要转码
		// 定义相关流
		// 用于浏览器下载响应
		OutputStream out = null;
		// 用于读压缩好的文件
		BufferedInputStream bis = null;// 用缓存性能会好一些
		// 用于压缩文件
		ZipOutputStream zos = null;
		String zipFilePath = zipBasePath + File.separator + fileName;
		File zipFile = new File(zipFilePath);
		try {
			if (!zipFile.exists()) {// 不存在创建一个新的
				zipFile.createNewFile();
			}
			out = response.getOutputStream();
			// 创建文件输出流
			zos = new ZipOutputStream(new FileOutputStream(zipFile));
			// 循环文件,一个一个按顺序压缩
			for (int i = 0; i < fileVector.size(); i++) {
				System.out.println(fileVector.get(i).getName() + "大小为:" + fileVector.get(i).length());
				FileUtil.zipFileFun(fileVector.get(i), root, zos);
			}
			// 压缩完成以后必须要在此处执行关闭 否则下载文件会有问题
			if (zos != null) {
				zos.closeEntry();
				zos.close();
				zos = null;
			}
			byte[] bt = new byte[10 * 1024];
			int size = 0;
			bis = new BufferedInputStream(new FileInputStream(zipFilePath), 10 * 1024);
			while ((size = bis.read(bt, 0, 10 * 1024)) != -1) {// 没有读完
				out.write(bt, 0, size);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {// 关闭相关流
			try {
				// 避免出异常时无法关闭
				if (zos != null) {
					zos.closeEntry();
					zos.close();
				}

				if (bis != null) {
					bis.close();
				}

				if (out != null) {
					out.close();
				}
				if (zipFile.exists()) {
					zipFile.delete();// 删除
				}
			} catch (Exception e2) {
				System.out.println("流关闭出错!");
			}

		}
		return "下载成功";
	}

}

package com.qjzh.lhiot.web.config.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;




public class FileUtil {
    /**
     * 把某个文件路径下面的文件包含文件夹压缩到一个文件下
     * @param file
     * @param rootPath 相对地址
     * @param zipoutputStream
     */
    public static void zipFileFun(File file,String rootPath,ZipOutputStream zipoutputStream){
        if(file.exists()){//文件存在才合法
            if(file.isFile()){
                //定义相关操作流
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    //设置文件夹
                    String relativeFilePath = file.getPath().replace(rootPath+File.separator, "");
                    //创建输入流读取文件
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis,10*1024);
                    //将文件装入zip中,开始打包
                    ZipEntry zipEntry;
                    if(!relativeFilePath.contains("\\")){
                        zipEntry = new ZipEntry(file.getName());//此处值不能重复,要唯一,否则同名文件会报错
                    }else{
                        zipEntry = new ZipEntry(relativeFilePath);//此处值不能重复,要唯一,否则同名文件会报错
                    }
                    zipoutputStream.putNextEntry(zipEntry);
                    //开始写文件
                    byte[] b = new byte[10*1024];
                    int size = 0;
                    while((size=bis.read(b,0,10*1024)) != -1){//没有读完
                        zipoutputStream.write(b,0,size);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    try {
                        //读完以后关闭相关流操作
                        if(bis != null){
                            bis.close();
                        }
                        if(fis != null){
                            fis.close();
                        }
                    } catch (Exception e2) {
                        System.out.println("流关闭错误!");
                    }
                }
            }
//            else{//如果是文件夹
//                try {
//                    File [] files = file.listFiles();//获取文件夹下的所有文件
//                    for(File f : files){
//                        zipFileFun(f,rootPath, zipoutputStream);
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                
//            }
        }
    }
    
    /*
     * 获取某个文件夹下的所有文件
     */
    public static Vector<File> getPathAllFiles(File file,Vector<File> vector){
        if(file.isFile()){//如果是文件,直接装载
            System.out.println("在迭代函数中文件"+file.getName()+"大小为:"+file.length());
            vector.add(file);
        }else{//文件夹
            File[] files = file.listFiles();
            for(File f : files){//递归
                if(f.isDirectory()){
                    getPathAllFiles(f,vector);
                }else{
                    System.out.println("在迭代函数中文件"+f.getName()+"大小为:"+f.length());
                    vector.add(f);
                }
            }
        }
        return vector;
    }
    
    /**
     * 压缩文件到指定文件夹
     * @param sourceFilePath 源地址
     * @param destinFilePath 目的地址
     * @param deleteSource  压缩后是否删除源文件
     */
    public static String zipFiles(String sourceFilePath,String destinFilePath, String fileName, boolean deleteSource){
        File sourceFile = new File(sourceFilePath);
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        fileName = fileName + ".zip";
        File destinFilePathFile = new File(destinFilePath);
        if (!destinFilePathFile.exists()) {
        	destinFilePathFile.mkdirs();
		}
        String zipFilePath = destinFilePath+File.separator+fileName;
        if (sourceFile.exists() == false) {
            System.out.println("待压缩的文件目录:" + sourceFilePath + "不存在.");
        } else {
            try {
                File zipFile = new File(zipFilePath);
                if (zipFile.exists()) {
                    System.out.println(zipFilePath + "目录下存在名字为:" + fileName + ".zip" + "打包文件.");
                } else {
                    File[] sourceFiles = sourceFile.listFiles();
                    if (null == sourceFiles || sourceFiles.length < 1) {
                        System.out.println("待压缩的文件目录:" + sourceFilePath + "里面不存在文件,无需压缩.");
                    } else {
                        //读取sourceFile下的所有文件
                        Vector<File> vector = FileUtil.getPathAllFiles(sourceFile, new Vector<File>()); 
                        fos = new FileOutputStream(zipFile);
                        zos = new ZipOutputStream(new BufferedOutputStream(fos));
                        byte[] bufs = new byte[1024 * 10];
                        
                        for (int i = 0; i < vector.size(); i++) {
                            // 创建ZIP实体,并添加进压缩包
                            ZipEntry zipEntry = new ZipEntry(vector.get(i).getName());//文件不可重名,否则会报错
                            zos.putNextEntry(zipEntry);
                            // 读取待压缩的文件并写进压缩包里
                            fis = new FileInputStream(vector.get(i));
                            bis = new BufferedInputStream(fis, 1024 * 10);
                            int read = 0;
                            while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
                                zos.write(bufs, 0, read);
                            }
                        }
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } finally {
            	//是否保留原文件
            	if(deleteSource) {
            		deleteDirectory(sourceFile);
            	}
                // 关闭流
                try {
                    if (null != bis)
                        bis.close();
                    if (null != zos)
                        zos.closeEntry();
                        zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
        return fileName;
    }
    
    /**
	 * 清理文件(目录或文件)
	 * @param file
	 */
	public static void deleteDirectory(File file){
		if(!file.exists()) return;
		
		if(file.isFile()){
			file.delete();//清理文件
		}else{
			File list[] = file.listFiles();
			if(list!=null){
				for(File f: list){
					deleteDirectory(f);
				}
				file.delete();//清理目录
			}
		}
	}
    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值