jQuery-File-Upload兼容IE8的问题:data.submit()没有发送请求

这段代码来自我的提问以及后来的回答。
https://segmentfault.com/q/1010000009635544

先给出此问题相关的代码:下面的代码,我已经成功兼容了IE9+,但是没能成功兼容IE8

先给出此问题相关的代码:
下面的代码,我已经成功兼容了IE9+,但是没能成功IE8,

这段的代码不需要关注。

 $("#file-upload").fileupload({           
            url: "/api/org/importOrg",
            add: function(e, data) {
                var file = data.files[0];
                $("#fileInput").val(file.name);
                $("#importSuccess").unbind().bind('click', function() {
                    if ($("#fileInput").val() === "") {
                        Messenger().post({
                            message: "请先上传文件!",
                            type: 'info',
                            showCloseButton: true
                        });
                        return;
                    }
                    if (browser == "Microsoft Internet Explorer" && (trim_Version == "MSIE7.0" )) {
                        Messenger().post({
                            message: '浏览器版本过老,不支持导入功能',
                            type: 'info',
                            showCloseButton: true
                        });
                        return;
                    } else if (!/.xls$|.xlsx$/.test(file.name)) {
                        Messenger().post({
                            message: '请上传以.xls/.xlsx为后缀名的正确Excel模版文件',
                            type: 'info',
                            showCloseButton: true
                        });
                        return;
                    } else if (file.size >= 10485760) {//上传文件大小不能超过10Mb
                        Messenger().post({
                            message: '上传的文件大小不能超过10Mb',
                            type: 'info',
                            showCloseButton: true
                        });
                        return;
                    }

                    $('#importSuccess').showLoading({
                        'overlayWidth': $('#importSuccess').innerWidth(),
                        'overlayHeight': $('#importSuccess').innerHeight()
                    });
                    //var pNode = pNodeSelectTree.getId();
                    //$("#file-upload").fileupload({formData: {name: $("#fileInput").val(), //type:$("[name=userType]:checked").val() }});
                    $("#file-upload").fileupload({
                        formData: {
                            name: $("#fileInput").val()
                        }
                    });
                    console.log('before submit:'+ $("#fileInput").val());//before submit:组织导入模板.xls
                    //$("#file-upload").fileupload({url:"/api/org/"+pNode[0]+"/importOrg"});
                    data.submit();
                    console.log("after submit");//after submit
                });
            },
            done: function(e, rep) {
                console.log("done");//没有触发fail,没触发done回掉
                var myResult=JSON.parse(rep.result);//后端返回字符串,解析成JSON对象,请求的content-type应该为text/plain,避免IE9下返回application/json提示下载,从而兼容IE9
              //  myResult={"failed":1,"succeed":10,"fails":[{"line":15,"name":"的萨芬","orgName":"组织","mobile":1352222222,"error":"出错啦!!!"},{"line":15,"name":"的萨芬","orgName":"组织","mobile":1352222222,"error":"出错啦!!!"},{"line":15,"name":"的萨芬","orgName":"组织","mobile":1352222222,"error":"出错啦!!!"}]};
                $('#importSuccess').hideLoading();
                $("#fileInput").val('');
                if (myResult.failed == 0) {
                    new Modal({
                        icon: "success",
                        title: "导入成功",
                        content: "成功导入" + myResult.succeed + "条数据",
                        isConfirm: false
                    }).show(function() {});
                } else {
                    $('#importErrorModal').html(importErrorModal(myResult));
                    new Modal('#importErrorModal').show();
                    $('#importErrorModal td>div').each(function(){
                      this.scrollWidth > this.offsetWidth && $(this).tooltip();
                    });
                    $('#importErrorModal .modal-header').moveAnimate({modalHeaders:'#importErrorModal .modal-header'});
                }

            },
            fail: function() {
                console.log("fail");//没有打印,也就是说没回调fail

                $('#importSuccess').hideLoading();
                $("#fileInput").val('');
            }
        });

我遇到的问题不是所谓的返回JSON数据,IE浏览器提示下载的问题,这个问题我已经解决了。
现在的问题是,在IE8下,此段程序无法回调done和fail函数,但是在IE9+浏览器和其他主流浏览器中是可行的。

  console.log('before submit:'+ $("#fileInput").val());//before submit:组织导入模板.xls
                    //$("#file-upload").fileupload({url:"/api/org/"+pNode[0]+"/importOrg"});
 data.submit();
 console.log("after submit");//after submit

根据上面那段程序的打印结果,说明add函数是成功执行的。
我也监控了network的通信,只有loading.gif这个表明正在加载的通信,没有其他相关的请求&&回复。

这也佐证了done和fail函数没有被回调,那么问题是什么呢?

我的回答:

IE9的兼容问题我已经在昨天尝试了一天被我解决,但是之后IE8的兼容问题一直没有被解决,虽然我也花了近一天的时间,在stack overflow上搜索相关问题,但是没有什么收获。

我是题主。我在这个问题上花了两个白天的时间,终于解决了这个问题。
之所以能解决这个问题,是因为我重新检查了前人写的代码逻辑。这个问题其实和HTML代码紧密相关,我之前只注意JS代码。
- HTML代码

<button class="btn btn-icon btn-blue" style="width:90px;height:32px" onclick="$(this).next().click()">
    <span class="icon-zcy icon-shangchuan mr" style="height:20px"></span>上传
</button>
<input type="file" name="files" style="display:none" class="btn-upload" id="file-upload" >

我们可以看到,这个其实是通过click触发click。
这个是很常见的手法,因为很难看,也不好定制(至少我不知道如何定制它的CSS)。所以通过隐藏input,通过button调用input成为大多数人的选择。
但是IE8出于安全性,不允许这么做,所以input看似被调用,但是没有获取到data, 下面这段英文来自微软关于IE的文档:

IE doesn’t allow manipulation of the type=”file” input element from javascript due to security reasons. Setting the filename or invoking a click event to show the browser dialog will result in an “Access is denied” error on the form submit.

这样如何保证安全性,我就不知道了。

所以为了避免这个限制,对HTML代码进行改动:看似在点击button,实则在点击
input

<div class="uploadFile">
    <input type="text" class="input input-medium" id="fileInput">                       
    <span>
        <a href="javascript:void(0)" class="btn btn-icon btn-blue"  > <span class="icon-zcy icon-shangchuan mr" style="height:20px"></span>上传</a>
        <input type="file" name="files" class="btn-upload" id="file-upload" >
     </span>
</div>

SASS

.uploadFile{
        span{
            position: relative;
            display: inline-block;
        }
        #file-upload { // 设置占据空间为0,看似点击button,实则在点击file-upload,从而避开IE8处于安全限制禁止间接点击input type=file的bug
            position: absolute;
            width: 100%;
            height: 100%;//和父元素同高宽
            top: 0;
            right: 0;
            opacity: 0;
            filter: alpha(opacity=0);
        }//解决此bug的方法详见http://wenzhixin.net.cn/2014/07/30/ie8_file_problem
    }

这是我看了这篇博客:http://wenzhixin.net.cn/2014/07/30/ie8_file_problem 后所做的尝试,然后works

我的感想:通过调试确定问题的根源,再根据问题在谷歌上搜答案。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="./CSS/index.css"> <script type="text/javascript" src="./js/jquery-3.3.1.js"></script> <title>Document</title> </head> <body> <div class="divclass"> <button onclick="getLogIn()">log in</button> <hr> <input type="file" id="uploadFile" name="uploadFile" /> <button onclick="addFile()" type="submit">提交</button> <hr> <input type="text" id="downloadfilename"> <button onclick="downloadFile()" target="new target">下载</button> </div> </body> <!-- http://127.0.0.1:8082/localTest/upload --> <!-- http://127.0.0.1:8082/localTest/testDownload --> <script> function getLogIn() { window.location.href = "./pages/login.html"; } function downloadFile() { var filename = document.getElementById("downloadfilename").value; //window.open("http://127.0.0.1:8082/localTest/testDownload?filename=" + encodeURI(filename)); window.open("http://127.0.0.1:8088/api/DownloadByCustomer?filename=" + encodeURI(filename)); } function addFile() { var formData = new FormData(); formData.append("file1", document.getElementById('uploadFile').files[0]); $.ajax({ url: 'http://127.0.0.1:8088/admApi/admUpload', type: 'POST', data: formData, // 上传formdata封装的数据包 //dataType: 'JSON', timeout: 10000, cache: false, // 不缓存 processData: false, // jQuery不要去处理发送的数据 contentType: false, // jQuery不要去设置Content-Type请求头 success: function (res) { console.log(res) console.log("上传成功"); return alert("上传成功"); }, error: function (sd) { console.log(sd) console.log("上传失败"); return alert("上传失败"); } }); }; </script> </html>
最新发布
06-03

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值