spingboot 实现单文件下载 以及多文件打包下载

最近一段时间一直在赶一个项目一直没有更新博客在写项目中有用到文件下载这块,还有打包下载

文件下载就是文件流形式 首先创建一个工具类

ZipFileUtil .java
/**
 * @Author zly
 * @Date 2019/3/12 18:57
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFileUtil {

    private ZipFileUtil() {
    }

    public static void doCompress(String srcFile, String zipFile) throws IOException {
        doCompress(new File(srcFile), new File(zipFile));
    }

    /**
     * 文件压缩
     *
     * @param srcFile 目录或者单个文件
     * @param zipFile 压缩后的ZIP文件
     */
    public static void doCompress(File srcFile, File zipFile) throws IOException {
        ZipOutputStream out = null;
        try {
            out = new ZipOutputStream(new FileOutputStream(zipFile));
            doCompress(srcFile, out);
        } catch (Exception e) {
            throw e;
        } finally {
            out.close();//记得关闭资源
        }
    }

    public static void doCompress(String filelName, ZipOutputStream out) throws IOException {
        doCompress(new File(filelName), out);
    }

    public static void doCompress(File file, ZipOutputStream out) throws IOException {
        doCompress(file, out, "");
    }

    public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException {
        if (inFile.isDirectory()) {
            File[] files = inFile.listFiles();
            if (files != null && files.length > 0) {
                for (File file : files) {
                    String name = inFile.getName();
                    if (!"".equals(dir)) {
                        name = dir + "/" + name;
                    }
                    ZipFileUtil.doCompress(file, out, name);
                }
            }
        } else {
            ZipFileUtil.doZip(inFile, out, dir);
        }
    }

    public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException {
        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);
        while ((len = fis.read(buffer)) > 0) {
            out.write(buffer, 0, len);
            out.flush();
        }
        out.closeEntry();
        fis.close();
    }


}

controller引用这个压缩工具

  /**
     * 根据fileId数组进行多文件打包下载
     *
     * @param fileIds
     * @param subProcessNo
     * @param certificateId
     * @param response
     * @param request
     * @throws IOException
     */
    //TODO 打包下载暂时不用
    @PostMapping("downLoad")
    //前端传入id数组
    public void downloadBatchByFile(@RequestBody List<String> fileIds, HttpServletResponse response,
                                    HttpServletRequest request) throws IOException {
        if (isNotEmpty(fileIds) && isNotEmpty(subProcessNo) && isNotEmpty(certificateId)) {
            User user = SessionUtil.getUser(request);
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setHeader("Content-Disposition", "attachment; filename=" + "整体大版本V1.0.zip");
            ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
            try {
                //                    ID数组进行循环遍历 查找文件
                for (String fileId : fileIds) {
                    AllFiles allFilesByFileId = allFilesService.getAllFilesByFileId(fileId);
                    ZipFileUtil.doCompress(filePath + allFilesByFileId.getFileName(), out);
                    response.flushBuffer();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                out.close();
            }
        }

    }
   response.setContentType("APPLICATION/OCTET-STREAM");
            response.setHeader("Content-Disposition", "attachment; filename=" + "整体大版本V1.0.zip");

这两段代码主要是设置响应的格式为二进制流,以及文件名(整体大版本V1.0.zip)

,返回的数据在ZipFileUtil.doCompress(file.getFilePath()+file.getFileName(), out) 这里面进行处理的

单个文件下载:

 /**
     * 根据文件名下载 以及在那个环节下载、属于哪个证件的材料
     *
     * @param fileId
     * @param subProcessNo
     * @param certificateId
     * @param response
     * @param request
     * @return
     * @throws Exception
     */
    //    单文件下载接口 暂时不去掉
    @GetMapping("download")
    @ApiOperation(value = "文件下载", notes = "根据文件Id")
    @ApiImplicitParam(name = "fileId", value = "ID", paramType = "path", required = true, dataType = "String")
    @SystemControllerLog(title = "文件下载", businessType = BusinessType.EXPORT)
    public ResponseEntity<byte[]> downLoad(@RequestParam("fileId") String fileId,
                                           @RequestParam("subProcessNo") Integer subProcessNo,
                                           @RequestParam("certificateId") Integer certificateId,
                                           HttpServletResponse response, HttpServletRequest request) throws Exception {
        User user = SessionUtil.getUser(request);
        HttpHeaders headers = new HttpHeaders();
        File file = null;
        if (isNotEmpty(fileId) && isNotEmpty(subProcessNo) && isNotEmpty(certificateId)) {
            AllFiles allFilesByFileId = allFilesService.getAllFilesByFileId(fileId);
//根据文件id找到文件的名称进行下载 String fileName
= allFilesByFileId.getFileName();
  //这里filePath实在配置文件配的 file
= new File(filePath + fileName); if (file.exists()) { //下载显示的文件名,解决中文名称乱码问题 String userAgent = request.getHeader("user-agent").toLowerCase(); String downloadFielName; if (userAgent.contains("msie") || userAgent.contains("like gecko")) { downloadFielName = URLEncoder.encode((fileName), "UTF-8"); } else { downloadFielName = new String((fileName).getBytes("UTF-8"), "iso-8859-1"); } headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + downloadFielName); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); } return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK); }

文件下载可以多种个人比较喜欢这种下载方式

 

posted @ 2019-03-19 14:05  BlackCatFish  阅读(383)  评论(0编辑  收藏  举报