FormData上传文件

by jsgoshu

HTML

<!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>FormData</title>
  </head>
  <body>
    <input id="file" type="file" />
  </body>
  <script>
    window.onload = function() {
      const file = document.querySelector("#file");
      file.onchange = function(e) {
        console.log(e.target.files);
        return;
        const xhr = new XMLHttpRequest();
        xhr.onload = function() {
          // 成功通信
          if (xhr.readyState === 4) {
            // 成功响应
            if (xhr.status === 200) {
              console.log(xhr.response);
            }
          }
        };
        xhr.open("post", "http://www.baidu.com");
        const formData = new FormData();

        formData.append("file", fileData);
        xhr.send(formData);
      };
    };
  </script>
</html>