前端 - jquery方式 / iframe +form 方式 上传文件

环境与上一章一样

jquery 方式上传文件:

HTML代码

    {#html代码开始#}
     <input type="file" id="img" >
     <button onclick="a1()">提交</button>
    {#html代码结束#}

jquery代码

    <script src="/static/js/jquery-1.12.4.min.js"></script>
    <script>
        function ax() {
            {#获取input file内的文件内容#}
            var img_data = document.getElementById('img').files[0];

            {#创建一个FormData对象,将数据append方式加入FormData对象中#}
            var dataX = new FormData();
            dataX.append('k1','11');
            dataX.append('k2','22');
            dataX.append('k3',img_data);
            
            {#ajax定义#}
            $.ajax(
                {
                    url:'/aj1.html',
                    type:'POST',
                    data:dataX,
                    success:function (arg) {
                        console.log(arg)
                    },
                    {#必加参数!!!!#}
                    processData:false,
                    contentType:false
                }
            )
        }
    </script>

 

iframe +form 方式上传文件:

HTML代码

{#    html代码开始#}
       <iframe id="ifr_id" name='ifr_na' style="display: none"></iframe>
        <form id='form_id' target="ifr_na" method="POST" action="/aj1.html"  enctype="multipart/form-data">
            <input type="file" name="k3">
            <button id="bt">提交</button>
        </form>
{#    html代码结束#}

js代码

    <script>
      document.getElementById('bt').onclick=function () {
          document.getElementById('ifr_id').onload = a3;
          document.getElementById('form_id').submit();
      };
       function a3() {
            console.log(this.contentWindow.document.body.innerText);
        };
    </script>

 

利用onchange事件 直接上传

{#    html代码开始#}
       <iframe id="ifr_id" name='ifr_na' style="display: none"></iframe>
        <form id='form_id' target="ifr_na" method="POST" action="/aj1.html"  enctype="multipart/form-data">
            <input type="file" name="k3">
        </form>
{#    html代码结束#}

    <script>
      document.getElementById('form_id').onchange=function () {
          document.getElementById('ifr_id').onload = a3;
          document.getElementById('form_id').submit();
      };
       function a3() {
            console.log(this.contentWindow.document.body.innerText);
        };
    </script>

 

posted @ 2018-11-05 21:37  Anec  阅读(502)  评论(0编辑  收藏  举报