导航


HTML

CSS

JavaScript

浏览器 & 网络

版本管理

框架

构建工具

TypeScript

性能优化

软实力

算法

UI、组件库

Node

冷门技能

form表单默认post请求的 enctype 为 application/x-www-form-urlencoded

<form 
	method="POST"
  action="server/upload.php"
  enctype="application/x-www-form-urlencoded">
  <input type="file" name="file" />
</form>

如果传文件,默认只是把文件名提交了,并不会提交文件:

Untitled

form 传文件

同步上传

单文件

<form 
	method="POST"
  action="server/upload.php"
  enctype="multipart/form-data">
  <input type="file" name="file" />
  <input type="submit" value="上传" />
</form>

多文件

<input type="file" name="file[]" multiple />

或者

<input type="file" name="file[]" />
<input type="file" name="file[]" />
<input type="file" name="file[]" />
<input type="file" name="file[]" />

FormData 构造函数

Untitled

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <input type="text" id="username" value="张三" />
  <input type="text" id="password" value="123" />
  <input type="submit" id="submitBtn" value="提交" />

  <script>
    var oUsername = document.getElementById("username"),
        oPassword = document.getElementById("password"),
        oSubmitBtn = document.getElementById("submitBtn"),
        fd = new FormData();

    oSubmitBtn.onclick = function() {
      fd.append("Username", oUsername.value);
      fd.append("Password", oPassword.value);

      console.log(fd);
      
      fd.set("Username", "李四");
      
      console.log("username: ", fd.get("Username"));
      console.log("password: ", fd.get("Password"));
    }
  </script>
</body>
</html>

多文件上传

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>多文件上传</title>
  <style>
    ul {
      padding: 0;
      margin: 0;
      list-style: none;
      margin-top: 100px;
    }

    .progress-bar {
      width: 300px;
      height: 40px;
      border: 1px solid #666;
      text-align: center;
    }

    .progress {
      width: 0%;
      height: 100%;
      background-color: green;
    }

    .error-info {
      line-height: 40px;
      font-size: 14px;
    }
  </style>
</head>
<body>
  <input type="file" id="file" multiple />

  <ul class="progress-wrap">
    <!-- <li class="progress-bar">
      <div class="progress"></div>
      <span class="error-info">文件类型错误</span>
    </li> -->
  </ul>

  <script>
    var oFile = document.getElementById("file"),
        oProgressWrap = document.getElementsByClassName("progress-wrap")[0];

    oFile.onchange = function() {
      var files = oFile.files,
          fileLen = files.length;
      console.log(oFile.files);

      if (fileLen <= 0) {
        console.log("您还没有选择图片");
        return;
      }

      if (fileLen > 5) {
        console.log("最多可同时上传5张图片");
        return;
      }

      var fileName = '',
          fileSize = 0,
          maxSize = 1024 * 1024 * 100, // 100M file返回的size是字节
          fd = null,
          errorInfo = '';

      for (var i = 0; i < fileLen; i++) {
        fileName = files[i].name;
        fileSize = files[i].size;

        // if (!/\\.(gif|jpg|jpeg|png)$/.test(fileName)) {
        //   errorInfo = '「'+ fileName + '」文件不是图片类型';
        // }

        if (fileSize > maxSize) {
          errorInfo = '「' + fileName + '」超过可上传大小';
        }

        var oProgressBar = document.createElement("li");
        oProgressBar.className = 'progress-bar';

        oProgressWrap.appendChild(oProgressBar);

        if (errorInfo !== '') {
          oProgressBar.innerHTML = '<span class="error-info">' + errorInfo + '</span>';
        } else {
          oProgressBar.innerHTML = '<div class="progress"></div>';

          fd = new FormData();
          fd.append('file', files[i]);

          var o = window.XMLHttpRequest
                    ? new XMLHttpRequest()
                    : new ActiveXObject("Microsoft.XMLHTTP");
          o.open("post", "server/upload.php");
          
          (function(i) {
            o.upload.onprogress = function(e) {
              var e = e || window.event,
                  percent = e.loaded / e.total * 100 + "%",
                  thisProgressBar = oProgressWrap.getElementsByClassName("progress-bar")[i];

              thisProgressBar.getElementsByClassName("progress")[0].style.width = percent;

              console.log(e); // e.loaded 是当前已上传的文件大小;e.total 是文件总大小
              console.log(percent);
            }
          })(i);

          o.send(fd);
        }
      }
    }
  </script>
</body>
</html>