1. 程式人生 > >前端 - jquery方式 / iframe +form 方式 上傳檔案

前端 - 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>