原生js配合ajax实现文件上传(兼容ie浏览器)

方法1:该方法适合ie9以上,因为ie9以上支持formdata。

页面代码:

<div class="step-panel" style="height:120px;position: relative">
    <div>
        <div class="import" id="import" οnclick="document.getElementById('articleImageFile').click();" style="width: 118px;height: 30px;text-align: center;line-height: 30px;background-color: #1890FF;color: white;border-radius: 5px;float: left;cursor:pointer;">导入csv</div>
        <div class="nameForFile" id="nameForFile" style="line-height: 30px;margin-left: 130px;color: black"></div>
        <input hidden id="articleImageFile" name="excelFile" type="file" class="x-file" accept=".xls,.xlsx">
    </div>
    <button class="sendSubmit" style="width: 118px;height: 30px;text-align: center;line-height: 30px;background-color: #1890FF;color: white;border-radius: 5px;cursor:pointer;position: absolute;top: 80px;left: 450px;display: none;border: none">发放卡券</button>
</div>

js模块代码:

importCards: function (obj) {
    var name = $("#articleImageFile").val();
    formData.append("file",$("#articleImageFile")[0].files[0]);
    formData.append("name",name);//可以使用formData.append()传递多个参数
    objName = obj.value;
    var fileName = objName.substring(objName.lastIndexOf(".")+1).toLowerCase();
    var fileRealName = checkStep1.getFileName(objName);
    $(".nameForFile").text(fileRealName)
    if(fileName !="xls" && fileName !="xlsx") {
        layer.msg("请选择Excel格式文件上传(xls、xlsx)!");
        obj.value = "";
        return false;   //阻止提交
    }else {
        $(".sendSubmit").css('display','block');
        console.log($("#articleImageFile")[0].value)
    }

},
sendCardsSubmit: function () {
    $.ajax({
        url :originUrl+ 'bind/batchBind/'+couponBatchId,
        type : 'POST',
        async : false,
        data : formData,
        // 告诉jQuery不要去处理发送的数据
        processData : false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType : false,
        beforeSend:function(){
            layer.load();
        },
        success : function(result) {
            console.log(result)
            if(result.result==0){
                layer.msg("发放成功!");
                $('.sendSubmit').attr('disabled', true)
            }else {
                layer.msg("发放失败!");
            }

        },
        complete: function () {
            layer.closeAll('loading');
        }
    });
}

方法二:该方法大多时候用在需要兼容低版本ie浏览器的时候

页面代码:

<form id="uploadFileForm" name="uploadFileForm" enctype="multipart/form-data" method="post">
            <input type="hidden" id="param1" name="param1" value="123"/>
            <input type="hidden" id="param2" name="param2" value="测试参数"/>
            <div id="uploadFileTableDiv" style="margin-left:10%;">
                <table border="1" width="80%">
                    <tr>
                       <td style="padding:10px;">
                          <span style="float:left;">上传文件:&nbsp;&nbsp;</span>
                       </td> 
                       <td style="padding:10px;"> 
                           <input type="file" id="attach" name="attach" size="25" style="height:30px;" />
                       </td>
                    </tr>
                    <tr>
                       <td colspan="2" style="padding:10px;padding-left:50px;">
                            <button id="submit_btn" type="button" class="btn btn-default" οnclick="javascript:submitFile();">
                                                                  上传文件
                            </button>
                       </td>     
                    </tr>
                </table>
            </div>
        </form>   

js代码:

function submitFile(){
    var attach = document.getElementById("attach").value;
    alert("attach: " + attach);

    if(attach == undefined || attach == ""){
        alert("请选择文件");
        return;
    }


    uploadFileForm.action = "/tools/uploadFileAction";
    uploadFileForm.submit();

}

这种方法会在提交的时候强制刷新页面,并且参数也不是很好获取,很是头疼,所以建议用方法3.

方法三:

页面代码:

<form id="uploadFileForm2" name="uploadFileForm2" enctype="multipart/form-data" method="post">
            <div id="uploadFileTableDiv2" style="margin-left:10%;">
                <table border="1" width="80%">
                    <tr>
                       <td style="padding:10px;">
                          <span style="float:left;">上传文件:&nbsp;&nbsp;</span>
                       </td> 
                       <td style="padding:10px;"> 
                           <input type="file" id="attach2" name="attach2" size="25" style="height:30px;" />
                       </td>
                    </tr>
                    <tr>
                       <td colspan="2" style="padding:10px;padding-left:50px;">
                            <button id="submit_btn2" type="button" class="btn btn-default" οnclick="javascript:ajaxSubmitFile();">
                                                                  上传文件
                            </button>
                       </td>     
                    </tr>
                </table>
            </div>
        </form>   

js代码:

//在表单上追加input hidden元素 存放其他参数
function appendInputElementForForm(formId,inputName,inputValue){
      var myh = document.createElement("input");   
      myh.type = "hidden";   
      myh.value = inputValue;   
      myh.id = inputName;   
      myh.name = inputName; 
      document.getElementById(formId).appendChild(myh);   
      alert(document.getElementById(inputName).value);   
}

//20170207 文件上传ajax Form表单提交
function ajaxSubmitFile(){
    var attach = document.getElementById("attach2").value;
    alert("ajaxSubmitFile attach2: " + attach);

    if(attach == undefined || attach == ""){
        alert("请选择文件");
        return;
    }

    appendInputElementForForm( "uploadFileForm2", "param1", "123");
    appendInputElementForForm( "uploadFileForm2", "param2", "测试参数");

    $(‘#uploadFileForm2‘).ajaxSubmit({
            type:"post",
            url:"/tools/ajaxUploadFileAction",
            data:$(‘#uploadFileForm2‘).serialize(),
            dataType:"json",
            error:function(data){
                alert(data);
            },
            success:function(data){
                alert("ajaxSubmit上传成功");
                alert("下载地址: " + data.data.attachment);
            }

    });     
}

这种方法主要用jquery.form.js支持的Ajaxsubmit进行文件上传,所以在用的时候要注意引进相关的依赖。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值