客户用IE批量下载文件文件到不同文件夹不压缩(包含分页带条件动态查询)

发布时间:2024年01月16日
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
    <script type="text/javascript" th:src="@{/vue/jQuery.js}"></script>
    <style>
        .login-box {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

        /* 模态框 */
        .login-box {
            display: none;
            width: 650px;
            height: 250px;
            border: 1px solid rgb(216, 216, 216);
            border-radius: 10px;
            box-shadow: 5px 5px 10px rgba(10, 20, 20, .2), -5px -5px 10px rgba(10, 20, 20, .2);
            background-color: #fff;
            /* 和遮罩层同理,模态框一定要在最上层 */
            z-index: 1;
        }

        .login-box .title {
            cursor: move;
            user-select: none; /* 禁止用户选中文字 */
            position: relative;
            width: 100%;
            height: 70px;
            color: #3f3f3f;
            font-size: 20px;
            font-weight: 700;
            text-align: center;
            line-height: 70px;
        }

        .login-box .title .exit {
            position: absolute;
            top: -10px;
            right: 10px;
            font-size: 30px;
        }

        .login-box .title .exit:hover {
            cursor: pointer;
            text-shadow: 2px 2px 4px rgba(10, 20, 20, .5);
        }

        .login-box #form {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            padding: 10px 0;
        }

        .login-box #form .input-box {
            width: 60%;
            height: 35px;
            margin-bottom: 20px;
            padding: 0px 10px;
            border: 1px solid #3f3f3f;
            border-radius: 8px;
            color: #3f3f3f;
            font-size: 16px;
            font-weight: 700;
        }

        .login-box #form .input-box:focus {
            outline: none;
        }

        .login-box #form .login-but {
            width: 120px;
            height: 35px;
            border: none;
            background-color: #fa8282;
            border-radius: 8px;
            color: #fff;
            font-size: 20px;
            font-weight: 700;
            margin-bottom: 20px;
        }

        .login-box #form .login-but:hover {
            background-color: #f36886;
        }

        /*    table表格*/
        table {
            width: 100%;
            border-collapse: collapse;
        }

        table caption {
            font-size: 2em;
            font-weight: bold;
            margin: 1em 0;
        }

        th, td {
            border: 1px solid #999;
            text-align: center;
            padding: 5px 0;
        }

        table thead tr {
            background-color: #008c8c;
            color: #fff;
        }

        table tbody tr:nth-child(odd) {
            background-color: #eee;
        }

        table tbody tr:hover {
            background-color: #ccc;
        }

        table tbody tr td:first-child {
            color: #f40;
        }

        table tfoot tr td {
            text-align: right;
            padding-right: 20px;
        }

    </style>
</head>
<body>
<div style="float: right">
    <a href="wlto_ForestHtml">林权档案下载</a>
    <a href="/getpdf/getPage">刷新到主页</a>
    <a href="/getpdf/getPicLog">图片下载日志</a>
    <a href="/getpdf/logAdminOUt">退出登录</a></div>
</div>
<br/>
<form action="#" onsubmit="return false;" style="text-align: center;margin: auto;">
    编号:<input type="text" id="v_aid" name="v_aid" style="width: 100px">
    坐落:<input type="text" id="v_location" name="v_location" style="width: 300px">
    <input type="submit" value="查询" onclick="selectData();">
</form>
<div>
    <br>
    <table border="1" id="messages_table" style="text-align: center;margin: auto;border-collapse: collapse;">
        <tr>
            <th><input type="checkbox" name="checkAll"></th>
            <th>序号</th>
            <th>编号</th>
            <th>档案号</th>
            <th>坐落</th>
            <th>档案下载时间</th>
            <th>下载人</th>
            <th>下载次数</th>

            <th>操作</th>
        </tr>
        <tr th:each="datas : ${page.list}">
            <td><input type="checkbox" name="item" th:value="${datas.aid}"></td>
            <td th:text="${datas.num}"></td>
            <td th:text="${datas.aid}"></td>
            <td th:text="${datas.docno}"></td>
            <td th:text="${datas.location}"></td>
            <td th:text="${#dates.format(datas.downtime,'yyyy-MM-dd')}"></td>
            <td th:text="${datas.downuser}"></td>
            <td th:text="${datas.downcount}"></td>
            <td>
                <a href="#" onclick="myFunction(this.getAttribute('data-id'))" th:data-id="${datas.aid}">下载</a>
            </td>
        </tr>
    </table>
</div>
<div style="text-align: center;margin: auto;">
    <a href="#" onclick="batchDown()">批量下载</a>
</div>
<!--引入page.html分页模板-->
<div th:insert="wl/page::page"></div>

<div class="login-box">
    <div class="title">
        图片下载
        <span class="exit">×</span>
    </div>
    <div id="form">
        <div>
            <input type="hidden" id="ywh">
            <div style="float: left;">
                <input type="text" id="path" style="width: 460px;" class="input-box" name="path" placeholder="选择下载路径"/>
            </div>
            <div style="float: right;margin-left:20px;">
                <input type=button class="login-but" style=" background-color:skyblue;" value="选择"
                       onclick="browseFolder('path')">
            </div>

        </div>
        <button id="btn" class="login-but" style="width: 260px; background-color:skyblue;"
                onclick="myFunction('batch')">下载
        </button>
    </div>

</div>
<script>

    let loginBox = document.querySelector('.login-box');
    //模态框
    let exit = document.querySelector('.exit');
    // 关闭模态框事件
    exit.addEventListener('click', function () {

        loginBox.style.display = "none";
    });

    let title = document.querySelector('.title');
    // 拖动标题区域可移动模态框
    title.addEventListener('mousedown', function (event) {
        // 计算鼠标在登录框中坐标
        let x = event.pageX - loginBox.offsetLeft;
        let y = event.pageY - loginBox.offsetTop;
        // 给页面添加鼠标移动事件
        document.addEventListener('mousemove', loginBoxMove);

        function loginBoxMove(event) {
            loginBox.style.left = (event.pageX - x) + "px";
            loginBox.style.top = (event.pageY - y) + "px";
        }

        // 鼠标松开后移除页面的鼠标移动事件
        document.addEventListener('mouseup', function () {
            document.removeEventListener('mousemove', loginBoxMove);
        })
    });

    /**
     * 用户自选文件夹 注意开启IE控件
     */
    function browseFolder(path) {
        try {
            var Message = "\u8bf7\u9009\u62e9\u6587\u4ef6\u5939"; //选择框提示信息
            debugger
            var Shell = new ActiveXObject("Shell.Application");
            var Folder = Shell.BrowseForFolder(0, Message, 64, 17); //起始目录为:我的电脑
            //var Folder = Shell.BrowseForFolder(0, Message, 0); //起始目录为:桌面
            if (Folder != null) {
                Folder = Folder.items(); // 返回 FolderItems 对象
                Folder = Folder.item(); // 返回 Folderitem 对象
                Folder = Folder.Path; // 返回路径
                if (Folder.charAt(Folder.length - 1) != "\\") {
                    // Folder = Folder + "\\";
                }
                document.getElementById(path).value = Folder;
                return Folder;
            }
        } catch (e) {
            alert(e.message);
        }
    }

    //下载
    //成功的文件
    var success = [];
    var s = 0;

    //失败的文件
    var fail = [];
    var f = 0;

    function myFunction(abth) {

        // 获取文件路劲
        var dPath = document.getElementById("path").value;
        //文件地址格式 C:\Users\lff\Desktop\客户机指定文件夹
        if (dPath == "") {
            alert("请先选择文件地址!!!")


            $('input[name="item"]').each(function () {
                if ($(this).val() == abth) {
                    $(this).prop("checked", true);
                }
            });
            loginBox.style.display = "block";
            return false;
        }

        if (abth == "batch") {
            // 文件名 多个
            var checkID = [];//定义一个空数组
            $("input[name='item']:checked").each(function (i) {//把所有被选中的复选框的值存入数组
                checkID[i] = $(this).val();
                console.log(checkID);
            });

            if (checkID.length == 0) {
                alert("请先勾选下载项或者点击单个下载");
                return false;
            }

            //循环调用方法
            for (var i = 0; i < checkID.length; i++) {
                //调用单个方法
                downFileOne(dPath, checkID[i]);

            }

            //展示下载结果
            alert("等待下载,共计" + checkID.length + "个档案流水号,请在文件中查看")
            loginBox.style.display = "none";
        } else {
            //单个下载
            downFileOne(dPath, abth);
            //展示下载结果
            alert(ywh + "已经下载成功");
            loginBox.style.display = "none";
        }
    }

    //单个业务编号下载
    function downFileOne(dPath, fileName) {

        console.log("输出" + dPath + "\\" + fileName);

        var fso;
        fso = new ActiveXObject("Scripting.FileSystemObject");
        //如果文件夹存在 覆盖
        console.log('操作:' + dPath + "\\" + fileName)
        var a = fso.FolderExists(dPath + "\\" + fileName);

        if (!a) {
            fso.CreateFolder(dPath + "\\" + fileName);
        } else {
            console.log("文件夹已经存在")
        }
        //fso.DeleteFolder (dPath+"\\"+fileName);
        //调用方法下载
        downloadFileByAjax("wlDownloadByJS", dPath, 0, fileName);
    }

    /**
     * 通过ajax下载文件
     *
     * @param {string} fileUrl 文件远程地址
     * @param {string} filePath 文件本地路径
     * @returns
     */

    function downloadFileByAjax(fileUrl, filePath, index, fileName) {

        if (filePath == null || filePath == undefined) {
            alert("请输入图片地址");
            return false;
        }

        if (fileName == null || fileName == undefined) {
            alert("请先选择档案");
            return false;
        }
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open('GET', fileUrl + "?index=" + index + "&fileName=" + fileName + "&timestamp=" + new Date().getTime(), true);

        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState === 4) {
                debugger
                var fName = decodeURI(xmlHttp.getResponseHeader("fileName"));
                var tempIndex = xmlHttp.getResponseHeader("index");
                //接受消息
                var msg = decodeURI(xmlHttp.getResponseHeader("msg"));
                console.log(msg);
                if (msg != "null") {
                    // alert(msg);

                    fail[f] = fileName;
                    f += 1;
                    var tmp_fso;
                    //下载失败  后删除文件夹
                    tmp_fso = new ActiveXObject("Scripting.FileSystemObject");
                    tmp_fso.DeleteFolder(filePath + "\\" + fileName);
                }

                console.log("fileName:" + fName);
                console.log("tempIndex:" + tempIndex);
                if (xmlHttp.status < 300 && xmlHttp.status >= 200) {
                    if (tempIndex == null || tempIndex == undefined) {
                        if (index > 0) {

                            success[s] = fileName;
                            s += 1;
                            // alert("下载成功!");
                        }
                        return false;
                    }
                    debugger
                    saveStreamToFile(xmlHttp.responseBody, filePath + "\\" + fileName + "\\" + fName);//******todo注意拼接路劲
                    debugger
                    downloadFileByAjax(fileUrl, filePath, tempIndex, fileName);
                } else {
                    alert("下载失败!");
                }
            }
        };

        xmlHttp.send();
    }


    /**
     * 保存二进制数据到文件
     *
     * @export
     * @param {*} stream
     * @param {string} filePath
     */
    function saveStreamToFile(stream, filePath) {
        saveContentToFile(stream, filePath, '1');
    }

    function saveContentToFile(content, filePath, type) {
        debugger
        //https://blog.csdn.net/haoranhaoshi/article/details/89671101

        var adodbstream = new ActiveXObject('ADODB.Stream');
        adodbstream.Mode = '3';
        adodbstream.Type = type;
        adodbstream.Open();
        if (type === '1') {
            adodbstream.Write(content);
        } else {
            adodbstream.WriteText(content);
        }
        var fn1 = 'SaveTo';
        var fn2 = 'File';
        adodbstream[fn1 + fn2](filePath, 2);
        adodbstream.Close();
    }


</script>


</body>
<script type="text/javascript" th:inline="javascript">
    var pageSizes = [[${page.pageSize}]];
    var pageNum = [[${page.pageNum}]]; //当前页
    var v_aid = "";
    var v_location = "";
    $(function () {
        (function ($) {
            $.getUrlParam = function (name) {

                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                var r = encodeURI(window.location.search).substr(1).match(reg);
                if (r != null)
                    return unescape(r[2]);
                return null;
            }
        })(jQuery);
        v_aid = decodeURI($.getUrlParam("aid"));
        v_location = decodeURI($.getUrlParam("location"));
        if (v_aid == null || v_aid == 'null') {
            v_aid = "";
        }
        if (v_location == null || v_location == 'null') {
            v_location = "";
        }

        $('#v_aid').val(v_aid);
        $('#v_location').val(v_location);


    });


    function batchDown() {
        //进入页面
        loginBox.style.display = "block";
    }

    function selectData() {
        var v_aid = $('#v_aid').val(), v_location = $('#v_location').val();
        window.location = encodeURI("wlto_ForestHtml?pageIndex=" + pageNum + "&pageSize=" + pageSizes + "&aid=" + v_aid + "&location=" + v_location);

        //window.location ="wlto_ForestHtml?pageIndex="+pageNum+"&pageSize="+pageSizes;
    }


    $("select#pageSizes").change(function () {

        pageSizes = this.value;
        //发个请求修改当前页面数量
        window.location = encodeURI("wlto_ForestHtml?pageIndex=" + pageNum + "&pageSize=" + pageSizes + "&aid=" + v_aid + "&location=" + v_location);
    });

    $("input[name='checkAll']").click(function () {
        if ($(this).is(':checked')) {
            $('input[name="item"]').each(function () {
                $(this).prop("checked", true);
            });
        } else {
            $('input[name="item"]').each(function () {
                $(this).prop("checked", false);
            });
        }
    });

    function toShowDownload(f) {
        window.location = encodeURI(window.location.pathname.substr(0, window.location.pathname.lastIndexOf("/")) + f + "&pageSize=" + pageSizes + "&aid=" + v_aid + "&location=" + v_location);
    }
</script>
</html>

page

<!DOCTYPE html>
<!--suppress ALL--> <!-- 去掉红色下划线-->
<html>
<div th:fragment="page">
    <style>
        .page {
            border: 1px solid blue;
            margin-right: 5px;
            padding: 3px 5px;
        }

        .page.active {
            color: red;
            border: 1px solid red;
        }
    </style>

    <div style="float: left">
        当前第<span th:text="${page.pageNum}"></span>页,
        每页<span th:text="${page.pageSize}"></span>条,

        <select name="pageSize" id="pageSizes"   style="width: 50px; height: 25px;">
            <option value="5" >5</option>
            <option value="10" >10</option>
            <option value="20" selected="selected" >20</option>
            <option value="40">40</option>
            <option value="80">80</option>
            <option value="100" >100</option>
            <option value="200">200</option>

        </select> 页行数,

        总记录数<span th:text="${page.total}"></span></div>
    <div style="float: right">
        <a href="#"  onclick="toShowDownload(this.getAttribute('data-id'))"  th:text="首页" th:if="${page.pageNum>1}" th:data-id="${path}" ></a>
        <a href="#" onclick="toShowDownload(this.getAttribute('data-id'))"  th:text="上一页" th:if="${page.pageNum>1}" th:data-id="${path}+${page.pageNum-1}"></a>

        <a href="#" onclick="toShowDownload(this.getAttribute('data-id'))"   th:data-id="${path}+${i}"
           th:each="i:${#numbers.sequence(page.pageNum<5?page.pageNum:page.pageNum-3,page.pageNum+5>=page.pages?page.pages:page.pageNum+5)}"
           th:text="${i}" th:class="${page.pageNum==i}? 'page active':'page'"></a>

        <a href="#" onclick="toShowDownload(this.getAttribute('data-id'))"   th:text="下一页" th:if="${page.pageNum<page.pages}" th:data-id="${path}+${page.pageNum+1}"></a>
        <a href="#" onclick="toShowDownload(this.getAttribute('data-id'))"   th:text="尾页" th:if="${page.pageNum<page.pages}"  th:data-id="${path}+${page.pages}"></a>
    </div>
</div>
</html>

package com.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mapper.ForestMapper;
import com.mapper.FtpserverMapper;
import com.model.Forest;
import com.model.ForestImg;
import com.model.Ftpserver;
import com.model.Pdf;
import com.service.ForestService;
import com.utils.FtpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cqwuliu
 * @Date: 2024/01/12/18:12  will_isme@163.com
 * @Description:
 */
@Service
@Slf4j
public class ForestServiceImpl implements ForestService {

    @Autowired
    private ForestMapper forestMapper;
    @Autowired
    private FtpserverMapper ftpserverMapper;

    @Override
    public PageInfo<Forest> getFindAll(Integer pageIndex, Integer pageSize, BigDecimal aid, String location) {
        String condition="";

        if(aid.compareTo(new BigDecimal("0"))==1){
            condition+=" and aid="+aid;

        }
        if(location!=null&&(!location.equals("null"))&&location.trim().length()>1){
            condition+=" and instr(t.卷题名,'"+location+"')>0 ";

        }

        PageHelper.startPage(pageIndex,pageSize);
        List<Forest> all   =  forestMapper.findByCondition(condition);


        PageInfo<Forest> ForestPageInfo = new PageInfo<>(all);
        return ForestPageInfo;
    }

    @Override
    public void wlDownloadByJS(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //输入的图片aid
        String aid=request.getParameter("fileName");
        if(aid==null){
            log.error("下载非法访问");
            return;
        }
        String i = request.getParameter("index") == null ? "" : request.getParameter("index");
        if (i==null ){
            log.error("下载非法访问");
            return ;
        }
        int index = Integer.parseInt(i);
        //目录下的文件
        //List<File> fileList = new ArrayList<>();

        List<ForestImg> fileList=forestMapper.findImgByPk1(new BigDecimal(aid));
        //将查找到的文件导入list
        //fileList.add(new File(jpegPath+"\\"+recordNo+"\\"+fname));
        if (index > fileList.size()-1){

            String uname= (String) request.getSession().getAttribute("realname");

            forestMapper.updatedownStatus(uname,new BigDecimal(aid));
            return ;
        }

        Ftpserver ftpserver=ftpserverMapper.getFtpInfoByServerid(fileList.get(index).getServerid());
        FtpUtils ftpUtils=new FtpUtils(ftpserver.getHost(), ftpserver.getPort(), ftpserver.getUsername(),ftpserver.getPassword());
        ByteArrayOutputStream byteArrayOutputStream = ftpUtils.getByteArrayOutputStream(fileList.get(index).getFolder(), fileList.get(index).getFilename());
       // saveimg(byteArrayOutputStream,fileList.get(index).getFilename());

//        //下载出现异常时,发送错误响应到前端
//        if (true){
//           String Msg="没有找到该档案文件请在档案系统查询了解";
//            response.setHeader("msg", URLEncoder.encode(Msg,"UTF-8").replaceAll("\\+", "%20"));//返回错误信息
//            log.info("没有找到该档案文件请在档案系统查询了解");
//            return;
//        }


        InputStream ins = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        BufferedInputStream bis = new BufferedInputStream(ins);


      //  BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("D:\\logs\\sydsunew\\aaa\\"+fileList.get(index).getFilename())));

        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("fileName", URLEncoder.encode(fileList.get(index).getFilename(), "UTF-8").replaceAll("\\+", "%20"));
        response.setHeader("index",index+1+"");

        ServletOutputStream outputStream = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(outputStream);
        int len = 0;
        byte[] buf = new byte[10 * 1024];
        while( (len=bis.read(buf, 0, buf.length)) != -1){
            bos.write(buf, 0, len);
        }
        bis.close();
        bos.flush();
        bos.close();




    }


    private void saveimg(ByteArrayOutputStream outputStream,String fname ){

        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream("D:\\logs\\aaa\\"+fname);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
          outputStream.writeTo(fileOutputStream);
        fileOutputStream.flush();
        fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

找到IE设置,添加到受信任网址,自定义级别,将activeX开启或者提示
跨域游览窗口和框架,通过域访问数据源,允许游览器控制的脚本运行

      <!--分页-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>
org.projectlombok lombok true
文章来源:https://blog.csdn.net/weixin_44873668/article/details/135629306
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。