java接口下载文件和多文件打包下载

单个文件下载

思路:先要获取文件路径,通过路径读取文件流,然后把流的信息写入HttpServletResponse类中

 

工具类方法

/**
     * 下载到本地
     *
     * @param file 待下载文件
     * @param response 通过controller注入的HttpServletResponse
     */
    public static void sendStream(File file, HttpServletResponse response, String fileName) {
        try {
            response.setContentType("multipart/form-data");
            //response.setContentType("multipart/form-data;charset=UTF-8");//也可以明确的设置一下UTF-8
            //设置响应头,控制浏览器下载该文件
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
            response.setHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "Content-Disposition");
            response.addHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "Accept-Ranges");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; fileName=" + URLEncoder.encode(
                    StringUtils.isNotBlank(fileName) ? fileName : file.getName(), "UTF-8"));
        } catch (Exception e) {
            logger.info("设置请求头出错:[{}]",e.getMessage());
        }
        BufferedInputStream is = null;
        OutputStream os = null;
        try {
            // 获取文件流
            is = new BufferedInputStream(new FileInputStream(file));

            int len = 0;
            byte[] data = new byte[2048];
            os = response.getOutputStream();
            while (-1 != (len = is.read(data, 0, data.length))) {
                os.write(data, 0, len);
                os.flush();
            }
        } catch (Exception e) {
            logger.info("下载时流操作出错[{}]", e);
        } finally {
            // 最后需要关闭流
            try {
                if (null != is) {
                    is.close();
                }
                if (null != os) {
                    os.close();
                }
            } catch (Exception e) {
                logger.error(String.format("流关闭出错了"), e);
            }
        }
    }

 

 

多文件打包下载

思路:和单个下载是类似的,只不过下载之前先把多个文件放到一个文件夹中,然后打包压缩成zip文件,再把zip文件流写入HttpServletResponse类中

/**
     *
     * @param response
     * @param split 文件路径数组
     */
    public void downloadFiles(HttpServletResponse response , String[] split){
// 多个文件打包下载
        String zipDirPath = PathUtils.concat(PathUtils.concat(templateDir, "zip"), "zipFileName");
        String zipFilePath = PathUtils.concat(templateDir, "zip");
        File zipDir = new File(zipDirPath);
        if (!zipDir.exists()) {
            zipDir.mkdirs();
        }
        for (int i = 0; i < split.length; i++) {
            File file = new File(split[i]);
            // 复制文件到对应的目录
            FileUtils.copyNewFile(zipDirPath, split[i], file.getName());
        }
        String zipPath = PathUtils.concat(zipFilePath,  "zipFileName.zip");
        try {
            //调用压缩方法
            ZipUtils.zip(zipDirPath, zipPath);
        } catch (IOException e) {
            logger.info("下载委托书打包操作发生错误[{}]", e);
            throw new BankException(ResponseInfo.CREATE_ZIP_ERROR);
        }
        // 获取压缩后的压缩包文件
        File zipFile = new File(zipPath);
        if (zipFile.exists()){
            // sendStream()方法同单个文件下载
            DownloadUtils.sendStream(zipFile, response, null);
        }

//删除对应的文件夹
        if (zipDir.exists()) {
            FileUtils.deleteDir(zipDir);
        }
    }

复制文件方法

   /**
     * 复制文件到对应目录
     *
     * @param dir      目标目录
     * @param filePath 文件路径
     * @param newName  新名字
     */
    public static void copyNewFile(String dir, String filePath, String newName) {
        File sourceFile = new File(filePath);
        if (newName == null) {
            newName = sourceFile.getName();
        }
        File toFile = new File(PathUtils.concat(dir, newName));
        if (toFile.exists()) {
            String prefix = newName.substring(newName.lastIndexOf("."));
            String sub = newName.substring(0, newName.lastIndexOf("."));
            // 递归
            copyNewFile(dir, filePath, getName(sub) + prefix);
        }
        try {
            Files.copy(sourceFile.toPath(), toFile.toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

压缩文件方法

/**
 * 压缩。
 * 
 * @param src
 *            源文件或者目录
 * @param dest
 *            压缩文件路径
 * @throws IOException
 */
public static void zip(String src, String dest) throws IOException {
   ZipOutputStream out = null;
   try {
      File outFile = new File(dest);
      out = new ZipOutputStream(outFile);
      out.setEncoding("UTF-8");
      File fileOrDirectory = new File(src);

      if (fileOrDirectory.isFile()) {
         zipFileOrDirectory(out, fileOrDirectory, "");
      } else {
         File[] entries = fileOrDirectory.listFiles();
         if (null != entries && entries.length > 0) {
            for (int i = 0; i < entries.length; i++) {
               // 递归压缩,更新curPaths
               zipFileOrDirectory(out, entries[i], "");
            }
         }
      }
   } finally {
      if (out != null) {
         try {
            out.close();
         } catch (IOException ex) {
            log.error(ex);
         }
      }
   }
}

 

获取本地文件某一文件夹下的所有文件名称(不含文件夹)

如果想要获取某文件夹内全部的文件,包括子级文件夹内的文件,可以方法递归一下就好了

/**
 * @author : swallow
 * @date : 2020/8/5 0005
 **/
public class FileTest {
    public static void main(String[] args) {
        List<File> files = getFiles("文件夹路径");
        for (File f : files) {
            System.out.println(f.getName());
        }
    }

    public static List<File> getFiles(String path) {
        File root = new File(path);
        List<File> files = new ArrayList<>();
        if (root.isDirectory()) {
            // 获取该文件夹下的所有文件
            File[] subFiles = root.listFiles();
            for (File f : subFiles) {
                if (!f.isDirectory()) {
                    // 添加到文件数组中
                     files.add(f);
                }
            }
        }
        return files;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值