文件下载接口,打包下载

发布于:2024-12-06 ⋅ 阅读:(152) ⋅ 点赞:(0)

一、单纯的下载一个文件,我这里是一个表格

前端调用接口

window.location.href = url+'download/'+id; 

后端接口

@RequestMapping(value = "/operation/download/{id}")
public void download(@PathVariable String id,HttpServletRequest request,HttpServletResponse response) throws Exception {
        //获取填充数据
        List<Map<String, Object>> result1 = new ArrayList<>();
        result1 = cmosCpcMonthTaskService.searchResultBySourceIdForExport(id);
        List<Map<String, Object>> result2 = new ArrayList<>();
        result2 = cmosCpcMonthTaskService.searchResult2BySourceIdForExport(id);

        Workbook workbook = new XSSFWorkbook();

        //生成表格
        Sheet sheet1 = workbook.createSheet("明细表");
        createSheet1(sheet1,result1);
        Sheet sheet2 = workbook.createSheet("总分表");
        createSheet2(sheet2,result2);

        String agent = request.getHeader("USER-AGENT");
        //设置表名
        String fileName = "反馈详情表";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-disposition,"attachment;filename= \"+fileName+\"");

        try(FileOutputStream fileout  = new FileOutputStream(currentPath+"/反馈详情表.xlsx") ){
            workbook.write(fileout);
        }

        workbook.close();

}

private void createSheet1(Sheet sheet, List<Map<String, Object>> result) {
        Row headerRow = sheet.createRow(0);
        String[] headers1 = {"所在党支部", "一级分类","工作事项及要求","完成情况大类","分值","工作联系人", "时限要求", "备注", "评价人", "反馈内容","反馈时间","状态"};
        for (int i = 0; i < headers1.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers1[i]);
        }
        sheet.setColumnWidth(0,30*256);
        sheet.setColumnWidth(1,30*256);
        sheet.setColumnWidth(2,30*256);
        sheet.setColumnWidth(7,30*256);
        sheet.setColumnWidth(9,30*256);
        sheet.setColumnWidth(10,30*256);


        int rowNum = 1;
        for (Map<String, Object> map : result) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue((String)map.get("ORG_ID"));
            row.createCell(1).setCellValue((String)map.get("LEVELONE"));
            row.createCell(2).setCellValue((String)map.get("TASK_CONTENT"));
            row.createCell(3).setCellValue((String)map.get("ATTRIBUTE_03"));
            row.createCell(4).setCellValue((String)map.getOrDefault("SCORE","0"));
            row.createCell(5).setCellValue((String)map.get("CONTACTPERSONS"));
            row.createCell(6).setCellValue((String)map.get("ATTRIBUTE_01"));
            row.createCell(7).setCellValue((String)map.get("MEMO"));
            row.createCell(8).setCellValue((String)map.get("EVALUATORS"));
            row.createCell(9).setCellValue((String)map.get("ATTRIBUTE_02"));
            row.createCell(10).setCellValue(map.get("LAST_UPDATE_DATE").toString());
            row.createCell(11).setCellValue((String)map.get("STATUS"));
        }
    }

    private void createSheet2(Sheet sheet, List<Map<String, Object>> result) {
        Row headerRow = sheet.createRow(0);
        String[] headers1 = {"支部序号","所在党支部", "总分"};
        for (int i = 0; i < headers1.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers1[i]);
        }
        sheet.setColumnWidth(1,30*256);
        int rowNum = 1;
        for (Map<String, Object> map : result) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue((String)map.get("ATTRIBUTE_03"));
            row.createCell(1).setCellValue((String)map.get("ORG_ID"));
            row.createCell(2).setCellValue(map.getOrDefault("SCORE","0").toString());
        }
    }

二、打包下载功能,生成表格,并将附件一起打包

后端接口开发:

@RequestMapping(value = "/operation/downloadExcel/{id}")
    public void downloadExcel1(@PathVariable String id,HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Map<String, Object>> result1 = new ArrayList<>();
        result1 = cmosCpcMonthTaskService.searchResultBySourceIdForExport(id);
        List<Map<String, Object>> result2 = new ArrayList<>();
        result2 = cmosCpcMonthTaskService.searchResult2BySourceIdForExport(id);

        Workbook workbook = new XSSFWorkbook();

        Sheet sheet1 = workbook.createSheet("明细表");
        createSheet1(sheet1,result1);
        Sheet sheet2 = workbook.createSheet("总分表");
        createSheet2(sheet2,result2);

        String tempDirName = id;
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        String currentPath =  rootPath + tempDirName + File.separator ;
        File currentPathFile = new File(currentPath);
        currentPathFile.mkdirs();

        try(FileOutputStream fileout  = new FileOutputStream(currentPath+"/反馈详情表.xlsx") ){
            workbook.write(fileout);
        }

        workbook.close();

        //获取附件
        List<String> downloadFileNames = new ArrayList<String>();
        List<String> fileIdArray = new ArrayList<>();
        List<CmosCpcTaskitemInstanceDTO> cmosCpcTaskitemInstanceDTOS = cmosCpcMonthTaskService.searchAllCmosCpcTaskitemInstanceBySourceId(id);
        for (CmosCpcTaskitemInstanceDTO cmosCpcTaskitemInstanceDTO : cmosCpcTaskitemInstanceDTOS) {
            if(!StringUtils.isEmpty(cmosCpcTaskitemInstanceDTO.getAttribute04())){
                fileIdArray.add(cmosCpcTaskitemInstanceDTO.getAttribute04());
            }
        }
        for(String fileId: fileIdArray){
            // 单个文件的逻辑与 download 一致
            FileOutputStream currentOutStream = null;
            //附件重命名
            String name = cmosCpcMonthTaskService.searchFileName(fileId);
            try {
                SysFileUpload file = swfUploadService.getAttachById(fileId);
                if (file != null) {
                    StringBuilder errorMsg = new StringBuilder();
                    // 下载到服务器,记录文件名
                    String fileName = file.getFILE_NAME();
                    downloadFileNames.add(fileName);
                    String ext = file.getFILE_TYPE();
                    File currentFile = new File(currentPath + name+"."+ext );
                    int cnt = 1;
                    while(currentFile.exists()){
                        // 同名文件处理规则 filename_1.ext, filename_2.ext ...
                        StringBuilder sb = new StringBuilder(fileName);
                        sb.insert(sb.lastIndexOf(ext)-1, "_"+ cnt++);
                        currentFile = new File(currentPath  + sb.toString() );
                    }
                    currentFile.createNewFile();
                    currentOutStream = new FileOutputStream(currentFile);
                    writeToOutputStream("false", file, currentOutStream);
                } else {
                    continue;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            finally {
                if(currentOutStream != null){
                    try{
                        currentOutStream.close();
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }
        }

        if(!currentPathFile.exists() || currentPathFile.list().length == 0){
            try(PrintWriter p = response.getWriter();){
                response.setCharacterEncoding("UTF-8");
                p.write("<script>alert('不允许下载当前附件');</script>");
            }catch (IOException e){
                e.printStackTrace();
            }
            deleteTempFile(new File[]{currentPathFile});
            return;
        }

        File[] fileArr = currentPathFile.listFiles();

        //创建一个zip文件
        String zipFileName = tempDirName + ".zip";
        File zipFile = new File(rootPath + zipFileName);
        ZipOutputStream zipOutputStream = null;
        boolean zipDone = false;
        try{
            zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile));
            zipFile(Arrays.asList(fileArr), zipOutputStream);
            zipDone = true;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(zipOutputStream != null){
                try{
                    zipOutputStream.close();

                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            //  删除文件及文件夹
            for(File file: fileArr){
                file.delete();
            }
            currentPathFile.delete();
        }
        // 如果压缩过程中出现异常,删除创建的压缩文件
        if(!zipDone){
            try(PrintWriter p = response.getWriter();){
                response.setCharacterEncoding("UTF-8");
                p.write("<script>alert('下载全部附件出错');</script>");
                deleteTempFile(new File[]{currentPathFile,zipFile});
                return;
            }catch (IOException e){
                e.printStackTrace();
            }
        }


        String downloadName = "下载.zip";
        response.setCharacterEncoding("UTF-8");
        String agent = request.getHeader("USER-AGENT");
        try(FileInputStream fis = new FileInputStream(zipFile);
            BufferedInputStream buff = new BufferedInputStream(fis);
            OutputStream myout = response.getOutputStream();// 从response对象中得到输出流,准备下载
        ){
            if(agent != null && agent.toLowerCase().indexOf("firefox") > 0)
            {
                response.setHeader("Content-Disposition", "attachment; filename="+ new String(downloadName.getBytes("GB2312"),"ISO-8859-1"));
            }else {
                response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(downloadName, "utf-8"));
            }
            response.setContentLength((int) zipFile.length());
            response.setContentType("application/zip");// 定义输出类型

            byte[] b = new byte[1024];// 相当于我们的缓存
            long k = 0;// 该值用于计算当前实际下载了多少字节

            // 开始循环下载
            while (k < zipFile.length()) {
                int j = buff.read(b, 0, 1024);
                k += j;
                myout.write(b, 0, j);
            }
            myout.flush();
            //buff.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        deleteTempFile(new File[]{currentPathFile,zipFile});
        //记录日志
        SysLogUtil.log("附件管理模块", SessionHelper.getLoginSysUser(request).getLoginName() + "下载附件:" + downloadFileNames.toString(),
                PlatformConstant.OpType.select, PlatformConstant.OpResult.success);

    }

    private void writeToOutputStream( String _allowEncry, SysFileUpload file, OutputStream outputStream) throws Exception{
        String fileId = file.getId();
        String filePath = file.getFILE_URL();
        String fastfdsLocation = file.getFastfdsLocation();
        //获取附件并写入outputStream
        FastDfsUtil.downLoadFileByStream(outputStream, fastfdsLocation);
    }

    private void zipFile(List<File> inputFiles, ZipOutputStream outputstream) throws IOException
    {
        for(File inputFile: inputFiles){
            BufferedInputStream bInStream = null;
             int i = 1;
            try{
                bInStream = new BufferedInputStream(new FileInputStream(inputFile));
                ZipEntry entry = new ZipEntry(inputFile.getName());
                outputstream.putNextEntry(entry);

                final int MAX_BYTE = 10 * 1024 * 1024; // 最大的流为10M
                long streamTotal = 0; // 接受流的容量
                int streamNum = 0; // 流需要分开的数量
                int leaveByte = 0; // 文件剩下的字符数
                byte[] inOutbyte; // byte数组接受文件的数据

                streamTotal = bInStream.available(); // 通过available方法取得流的最大字符数
                streamNum = (int) Math.floor(streamTotal / MAX_BYTE); // 取得流文件需要分开的数量
                leaveByte = (int) streamTotal % MAX_BYTE; // 分开文件之后,剩余的数量

                if (streamNum > 0) {
                    for (int j = 0; j < streamNum; ++j) {
                        inOutbyte = new byte[MAX_BYTE];
                        // 读入流,保存在byte数组
                        bInStream.read(inOutbyte, 0, MAX_BYTE);
                        outputstream.write(inOutbyte, 0, MAX_BYTE);
                    }
                }
                // 写出剩下的流数据
                inOutbyte = new byte[leaveByte];
                bInStream.read(inOutbyte, 0, leaveByte);
                outputstream.write(inOutbyte);
                outputstream.closeEntry();
            }catch (IOException e){
                throw e;
            }finally {
                if(bInStream != null){
                    try{
                        bInStream.close();
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }
            i++;
        }
    }


    private void createSheet1(Sheet sheet, List<Map<String, Object>> result) {
        Row headerRow = sheet.createRow(0);
        String[] headers1 = {"所在党支部", "一级分类","工作事项及要求","完成情况大类","分值","工作联系人", "时限要求", "备注", "评价人", "反馈内容","反馈时间","状态"};
        for (int i = 0; i < headers1.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers1[i]);
        }
        sheet.setColumnWidth(0,30*256);
        sheet.setColumnWidth(1,30*256);
        sheet.setColumnWidth(2,30*256);
        sheet.setColumnWidth(7,30*256);
        sheet.setColumnWidth(9,30*256);
        sheet.setColumnWidth(10,30*256);


        int rowNum = 1;
        for (Map<String, Object> map : result) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue((String)map.get("ORG_ID"));
            row.createCell(1).setCellValue((String)map.get("LEVELONE"));
            row.createCell(2).setCellValue((String)map.get("TASK_CONTENT"));
            row.createCell(3).setCellValue((String)map.get("ATTRIBUTE_03"));
            row.createCell(4).setCellValue((String)map.getOrDefault("SCORE","0"));
            row.createCell(5).setCellValue((String)map.get("CONTACTPERSONS"));
            row.createCell(6).setCellValue((String)map.get("ATTRIBUTE_01"));
            row.createCell(7).setCellValue((String)map.get("MEMO"));
            row.createCell(8).setCellValue((String)map.get("EVALUATORS"));
            row.createCell(9).setCellValue((String)map.get("ATTRIBUTE_02"));
            row.createCell(10).setCellValue(map.get("LAST_UPDATE_DATE").toString());
            row.createCell(11).setCellValue((String)map.get("STATUS"));
        }
    }

    private void createSheet2(Sheet sheet, List<Map<String, Object>> result) {
        Row headerRow = sheet.createRow(0);
        String[] headers1 = {"支部序号","所在党支部", "总分"};
        for (int i = 0; i < headers1.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers1[i]);
        }
        sheet.setColumnWidth(1,30*256);
        int rowNum = 1;
        for (Map<String, Object> map : result) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue((String)map.get("ATTRIBUTE_03"));
            row.createCell(1).setCellValue((String)map.get("ORG_ID"));
            row.createCell(2).setCellValue(map.getOrDefault("SCORE","0").toString());
        }
    }


    private void deleteTempFile(File[] files){
        for(File file : files){
            if(!file.exists()){
                continue;
            }

            if(file.isDirectory()){
                File[] subFile = file.listFiles();
                deleteTempFile(subFile);
            }
            file.delete();
        }
    }

   
}

网站公告

今日签到

点亮在社区的每一天
去签到