ajax请求_通过url下载文件_文件打zip包下载桌面_压缩下载_打包

该博客详细介绍了如何在前端通过Ajax触发文件下载请求,并在后端实现文件的Zip打包及删除临时文件的过程。前端利用jQuery的Ajax发送GET请求,后端接收到请求后查询文件信息,下载并存储到临时文件夹,然后进行Zip打包,最后通过HttpServletResponse响应到客户端。同时,博客还包含了异常处理和临时文件的清理机制。
摘要由CSDN通过智能技术生成

1.1前端单击时间触发ajax请求
在这里插入图片描述
1.2ajax请求


    var downloadRecord = function (caseNo) {
        $.ajax({
            type: 'GET',
            url: '${ctx}/downLoadRecordZip.json',
            async: false,
            data: {
                'caseId': caseNo
            },
            success: function () {
                var downloadUrl = '${ctx}/downLoadRecordZip.json?caseId=' + caseNo;
                window.location.href = downloadUrl;
            },
            error: function () {
                alert("文书不存在!")
            }
        });
    };

2通过url下载文件,打zip包,删除临时文件夹

@Controller
public class RecordInfoController {

    @Autowired
    private RecordInfoService recordInfoService;

    private static final Logger logger = LoggerFactory.getLogger(RecordInfoController.class);

    /**
     * 1.查询信息得到url
     * 2.创建临时文件夹,用于存放多个文件
     * 3.通过url下载文件,储存在文件夹中
     * 4.多个文件下载完成,打包zip(通过response响应,下载到桌面)
     * 5.删除临时目录中所有文件以及文件夹
     *
     * @param caseId
     * @return
     */
    @RequestMapping(value = "downLoadRecordZip", method = RequestMethod.GET)
    @Consumes({ MediaType.APPLICATION_FORM_URLENCODED })  //"application/x-www-form-urlencoded"
    @Produces({ MediaType.APPLICATION_OCTET_STREAM })   //"application/octet-stream";
    public void downLoadZip(String caseId, HttpServletResponse response) throws UnsupportedEncodingException {

        logger.info("下载案件文书 , 案件编号为 : " + caseId);

        List<RecordInfo> recordInfoList = recordInfoService.findRecordByCaseId(caseId);

        String name = "";
        File dir = null;
        if (recordInfoList.size() > 0) {


            //创建临时文件
            String tempDirPath = FilenameUtils.concat(FileUtils.getTempDirectory().getPath(), UUID.randomUUID().toString());
            logger.info("临时文件夹路径为 : " + tempDirPath);
            dir = new File(tempDirPath);
            if (!dir.exists()) {
                dir.mkdir();
            }

            //遍历下载文件
            for (RecordInfo recordInfo : recordInfoList) {

                String fjdz = recordInfo.getFjdz();
                logger.info("附件地址为 : " + fjdz);
                //设置压缩后的文件名
                String fileName = recordInfo.getWjmc();
                logger.info("文件名称为 : " + fileName);
                if (fileName == null) {
                    throw new RuntimeException("文件名称为空");
                }

                //通过url地址获取连接
                URL url = null;

                try {
                    url = new URL(fjdz);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    //设置超时时间为3秒
                    conn.setConnectTimeout(3000);

                    //防止抓包程序抓取而返回403错误
                    conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                    conn.setRequestMethod("GET");
                    conn.connect();

                    //通过连接获取到输入流
                    InputStream inputStream = conn.getInputStream();
					//文件后缀名
                    name = fileName.substring(0, fileName.lastIndexOf("."));
                    System.out.println("name : " + name);

                    //将输入流输出到临时文件夹中
                    File file = new File(FilenameUtils.concat((tempDirPath), fileName));
                    logger.info("文件路径为 : " + file.getAbsolutePath());
                    FileUtils.copyInputStreamToFile(inputStream, file);

                    inputStream.close();
                } catch (Exception e) {
                    logger.error("下载文件失败 , 案件编号为 : " + caseId);
                    throw new RuntimeException("下载文件失败");
                }
            }

            //zip打包
            //zip文件名称
            String zipFileNmae = caseId + "-" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + ".zip";
            logger.info("zip文件名称 : " + zipFileNmae);
            //指定zip下载位置
            //File zipFile = new File(tempDirPath + File.separator + zipFileNmae);
            try {
                //设置content-disposition 响应头控制浏览器以附件保存,(attachment : 附件保存 ; inline 在线打开)
                // 中文名称编码,防止中文乱码
                //response.setContentType("application/octet-stream");
                response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(zipFileNmae, "utf-8"));
                //响应到桌面
                ServletOutputStream outputStream = response.getOutputStream();
                //zip流
                ZipOutputStream zos = new ZipOutputStream(outputStream);
                BufferedOutputStream bos = new BufferedOutputStream(zos);
                File[] files = dir.listFiles();
                if (files != null && files.length != 0) {
                    for (File file : files) {
                    	//获取文件输入流
                        FileInputStream inputStream = new FileInputStream(file);
                        //zip打包放文件
                        zos.putNextEntry(new ZipEntry(file.getName()));
                        int b;
                        // 将字节流写入当前zip目录
                        while ((b = inputStream.read()) != -1) {
                            bos.write(b);
                        }
                        bos.flush();
                        inputStream.close();
                    }
                }
                bos.close();
            } catch (Exception e) {
                logger.error("zip打包异常 , 案件编号为 : " + caseId);
                throw new RuntimeException("zip打包异常");
            }

            //文件下载响应到桌面之后,删除下载的文件
            deletAllFiles(new File(tempDirPath));

        }else{
            throw new RuntimeException("文书不存在");
        }
    }

    /**
     * 递归删除文件目录及文件
     *
     * @param file
     */
    public static void deletAllFiles(File file) {
        if (file == null) {
            return;
        }
        //文件目录存在(包括文件及文件夹)
        if (file.exists()) {
            //文件
            if (file.isFile()) {

                logger.info("删除文件 : " + file.getName());
                file.delete();

            } else if (file.isDirectory()) {     //是文件夹

                //接收文件夹目录下所有的文件实例
                File[] listFiles = file.listFiles();
                //文件夹为空 递归出口
                if (listFiles == null) {
                    return;
                }
                for (File file2 : listFiles) {
                    //foreach遍历删除文件 递归
                    deletAllFiles(file2);
                }

                //递归跳出来的时候删除空文件夹
                logger.info("删除文件夹  : " + file.getAbsolutePath());
                file.delete();
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值