3.2 傳送檔案資料

API: 傳檔

POST https://notes.webmix.cc/html5_tutorial/file/file_receive.php

Request Body

NameTypeDescription

the_file*

File 物件

傳遞檔案

建立 ajax/practice/upload_file_xmlhttprequest.html 檔案,內容如下:

<!DOCTYPE html>
<html lang="zh-Hant">
  <head>
    <meta charset="utf-8">
    <title>AJAX: 檔案上傳進度顯示</title>
  </head>
  <body>

    <input type="file" id="the_file" accept="image/*">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>

      $(function(){

        $("#the_file").on("change", function(e){

          let xhr = new XMLHttpRequest();

          // 1. 改成 POST,然後帶入 API 網址
          xhr.open("POST", "https://notes.webmix.cc/html5_tutorial/file/file_receive.php", true);

          xhr.addEventListener("load", function(){
            alert("檔案傳送完成");
          });

          xhr.addEventListener("error", function(){
            console.log("執行到 error 程式");
          });

          xhr.addEventListener("loadend", function(){
            alert("執行到 loadend 程式");
          });

          // 2. 綁定 progress 事件,用來監控傳檔的進度
          xhr.upload.addEventListener('progress', function(evt) {

            // evt.lengthComputable: 是否可被計算
            // evt.loaded: 已傳了多少
            // evt.total: 總共有多少要傳

            if (evt.lengthComputable) {

              var loaded = (evt.loaded / evt.total);
              if (loaded <= 1) {
                var percent = loaded * 100;
                console.log("進度:" + percent + "%");
              }

            }

          });

          // 3. 將資料,跟著請求(request)發送出去
          //<form enctype="multipart/form-data">
            //<input type="file" name="the_file">
          //</form>
          let form_data = new FormData();
          form_data.append('the_file', this.files[0]);
          xhr.send(form_data);

        });
      
      });
    </script>
  </body>
</html>

Last updated