Form表单提交下载文件并监控下载状态

本文介绍了如何在React应用中利用form表单提交来触发文件下载,并通过监控iframe来获取下载状态。关键点在于设置form表单的target属性与iframe的id相同,以便将提交结果放入iframe中。在下载完成后,可以通过访问iframe的document.body.innerHTML来获取返回值,从而实现状态监控。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下载

recordsClick(){//导出表格
    var params = {// 参数
        id:xx,
        name:xx
    };

    var form = document.createElement('form')
    form.id = 'form'
    form.name = 'form'
    document.body.appendChild (form)
    for (var obj in params) {
        if (params.hasOwnProperty(obj)) {
            var input = document.createElement('input')
            input.tpye='hidden'
            input.name = obj;
            input.value = params[obj]
            form.appendChild(input)
        }
    }
    form.method = "GET" //请求方式
    form.action = runEnv.api_url+'请求地址'
    form.submit()
    document.body.removeChild(form)
},

监控下载状态

注意关键点:

<form id="form_addcompress" action="/rest/upload" method="post" enctype="multipart/form-data" target="uploadframe">
<iframe id="uploadframe" name="uploadframe" style="display:none"></iframe></div>
var timeSet=setInterval(function(){
//定时刷新监控iframe里有没有被写入后台数据
        time_index++;
        var iframeObj = $(window.frames["uploadframe"].document); 
        var val=iframeObj.find("body").html();
        if(val!=""&&time_index<5){
          var _result=eval("(" + val + ")");
          if(typeof _result.code!="undefined"&&_result.code=="0"){
            clearInterval(settime);
            return false;
          }else{
            $.modaldialog.smallTip("上传失败", {
                x: event.pageX,
                y: event.pageY
            });
            clearInterval(timeSet);
          }
        }else{
          clearInterval(timeSet);
        }
      },1000);

form表单中的target=”uploadframe“与iframe中的id=”uploadframe“要一致;原因:target指form表单提交后返回结果要放的位置;
$(window.frames[“uploadframe”].document).find(“body”).html()结果是form提交后的返回值,用循环来找值;
下面是基于react自己封装的一个方法,可参考

/**
 * form下载
 * 参数:
 * {
 *     params: {             // 操作需要的参数
 *          billId: '',
 *          ...
 *     },
 *     url: '',             // 操作的url
 *     enctype: 1/2/3       // form提交的方式  1和默认、multipart/form-data 2、application/x-www-form-urlencoded 3、text/plain
 * }
 */
import { ajax, output,toast, base, getPlatformLang, formDownload, gzip, viewModel } from 'nc-lightapp-front';

export default function handleDownload({
                                           newProps,
                                           params,
                                           url,
                                           enctype
                                       }) {
    // 从ajax哪里取得,目的获取busiaction
    var app = '', appcode = '';
    let appN = window.parent.location.hash.split("?");
    if (appN && appN[1]) {
        let appPrams = appN[1].split('&');
        if (appPrams && appPrams instanceof Array) {
            appPrams.forEach((item) => {
                if (item.indexOf('=') != -1 && item.split('=') && item.split('=') instanceof Array) {
                    if (item.split('=')[0] === 'n') {
                        if (item.split('=')[1]) {
                            app = decodeURIComponent(decodeURIComponent(item.split('=')[1]));
                        }
                    }
                    if (item.split('=')[0] === 'c') {
                        if (item.split('=')[1]) {
                            appcode = decodeURIComponent(decodeURIComponent(item.split('=')[1]));
                        }
                    }
                }
            });
        }
    }

    let busiaction = `${app || null}-${window.actionName || null}`;
    const sysParamJson = {
        sys_busiaction: busiaction,
        sys_appcode: appcode,
        sys_ts: new Date().getTime()
        // busiaction: busiaction ,
        // appcode: appcode,
        // ts: new Date().getTime()
    }
    enctype = ((type) => {
        switch (type) {
            case 1:
                return 'multipart/form-data';
            case 2:
                return 'application/x-www-form-urlencoded';
            case 3:
                return 'text/plain';
            default:
                return 'multipart/form-data';
        }
    })(enctype)

    const [attrs, el_form] = [
        {
            target: 'printServiceframe',//'_blank',
            method: 'POST',
            enctype,
            type: 'hidden',
            action: url || ''
        },
        document.createElement('form')
    ];
    Object.assign(el_form, attrs);
    const config = {...params, ...sysParamJson}
    for (let key in config) {
        if (config[key] instanceof Array) {
            config[key].forEach((item, index) => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = key;
                input.value = item;
                //el_form.append(input);
                el_form.appendChild(input);
            })
        } else {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = key;
            input.value = config[key];
            //el_form.append(input);
            el_form.appendChild(input);
        }
    }
    //document.body.append(el_form);
    document.body.appendChild(el_form);
    // let submitData = ''
    // for (let item of Object.keys(config)) {
    //     submitData += `${item}=${config[item]}&&`
    // }
    /*ajax({
        method: 'post',
        url: url,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        data: submitData.slice(0, -2),
        success: (res) => {
            if (res.data) {
                var newWin = window.open('');//新开页面
                if (newWin) {
                    newWin.document.write(res.data);//输入要打印的内容
                    newWin.print();
                    newWin.close();
                } else {
                    toast({color: 'warning', content: '您的浏览器阻止了弹出式窗口,请查看浏览器设置'});
                }
            }
        },
        error: (err) => {
            toast({color: 'warning', content: err});
        }
    })*/
    el_form.submit();
    document.body.removeChild(el_form);
    let timer = setInterval( () => {
      let $frame = document.querySelector("#printServiceframe");
      let frameWin = $frame.contentWindow;
      if(frameWin.document.querySelector("#error") || frameWin.document.querySelector("#success")) {
        clearInterval(timer);
        if(frameWin.document.querySelector("#error")) {
          let errMsg = frameWin.document.querySelector("#error").innerHTML;
          console.log(errMsg)
          newProps.openTo("/uap/printExeDown/ExeDownload/main/index.html?pk_message=dd", { appcode: params.appcode, pagecode: params.pagecode,actionUrl:url});
        }else {
          let succMsg = frameWin.document.querySelector("#success").innerHTML;
          console.log(succMsg)
          let newWin = window.open("");
          newWin.document.title = "打印反馈";
          newWin.document.body.innerHTML = "打印成功";
        }
      }
    }, 1500)
    return false;
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值