1. 程式人生 > >原生javascript實現檔案上傳功能程式碼

原生javascript實現檔案上傳功能程式碼

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
      *{margin:0;padding:0;}
      .progress {
            width: 300px;
            height: 20px;
            border: 1px solid hotpink;
            border-radius: 20px;
            overflow: hidden;
        }
                                            
        .step {
            height: 100%;
            width: 0;
            background: greenyellow;
        }
  </style>
</head>
<body>
  <div class='progress'>
    <div class="step"></div>
</div>
<input type="file" name='icon' id="file">
<input type="button" value='ajax2.0'>
</body>
<script>
   //  如果我們要使用 ajax2.0 結合FormData 來提交資料 必須使用 post
   document.querySelector('input[type=button]').onclick = function () {
        //1.建立物件
        var xhr = new XMLHttpRequest();
        //2.設定請求行(get請求資料寫在url後面)
        xhr.open('post', './test.php');
        //3.設定請求頭(get請求可以省略,post不傳送資料也可以省略)
        // 如果使用的時 formData可以不寫 請求頭 寫了 無法正常上傳檔案
        //  xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        //3.5註冊回撥函式
        xhr.onload = function () {
            console.log(xhr.responseText);
        }
        // XHR2.0新增 上傳進度監控
        xhr.upload.onprogress = function (event) {
            //  console.log(event);
            var percent = event.loaded / event.total * 100 + '%';
            console.log(percent);
            // 設定 進度條內部step的 寬度
            document.querySelector('.step').style.width = percent;
        }
        // XHR2.0新增 
        var form = document.createElement('form');
        form.appendChild(document.querySelector('#file'));
        var data = new FormData(form);
        data.append('name', 'zhangsan');   // 新增其他引數
        data.append('age', 19); // 新增其他引數
        //4.請求主體傳送(get請求為空,或者寫null,post請求資料寫在這裡,如果沒有資料,直接為空或者寫null)
        xhr.send(data);
    }
</script>
</html>
<?php     
// 獲取提交的檔案資訊
    print_r($_FILES); 


    // 儲存上傳的資料
    move_uploaded_file($_FILES['icon']['tmp_name'],'./files/'.$_FILES['icon']['name']);
?>