文件上传基本写法

63 阅读1分钟
  1. 多文件传输
<div>
      <h2>多文件上传</h2>
      <input type="file" id="f1" name="file" multiple />
      <button type="button" id="btn-submit">上传</button>
    </div>

    <script>
      var btn = document.getElementById('btn-submit')
      btn.addEventListener('click', submitUpload)

      function submitUpload() {
        // 获得文件列表,注意这里不是数组,而是对象
        // 获得一个FileList 对象:包含了文件的名称,大小,修改时间等
        var files = document.getElementById('f1').files
        // 判断是否选择了文件
        if (!files.length) {
          console.log('请选择上传的文件')
          return
        }
        // console.log(files.length)
        var fd = new FormData()
        for (let i = 0; i < files.length; i++) {
          fd.append('file', files[i])
        }
        // 创建xhr对象
        var xhr = new XMLHttpRequest()
        var url = 'http://localhost:9000/upload'
        xhr.open('POST', url, true)
        xhr.send(fd)

        xhr.onreadystatechange = function () {
          if (xhr.readyState == 4 && xhr.status == 200) {
            var res = JSON.parse(xhr.responseText)
            console.log(res)
          }
        }
      }
    </script>
  1. 带进度条的
<!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>
      #progress {
        height: 20px;
        width: 300px;
        margin-bottom: 30px;
      }
      #progress span {
        display: block;
        height: 20px;
        width: 0;
        color: #fff;
        font-size: 12px;
      }

      .red {
        background-color: red;
      }

      .green {
        background-color: green;
      }
    </style>
  </head>
  <body>
    <div>
      <h2>多文件上传</h2>
      <input type="file" id="f1" name="file" multiple />
      <div id="progress">
        <span class="red"></span>
      </div>
      <button type="button" id="btn-submit">上传</button>
    </div>

    <script>
      var btn = document.getElementById('btn-submit')
      btn.addEventListener('click', submitUpload)

      function submitUpload() {
        // 进度条对象
        var progressSpan = document.getElementById('progress').firstElementChild
        progressSpan.style.width = '0'
        progressSpan.classList.remove('green')
        // 获得文件列表,注意这里不是数组,而是对象
        // 获得一个FileList 对象:包含了文件的名称,大小,修改时间等
        var files = document.getElementById('f1').files
        // 判断是否选择了文件
        if (!files.length) {
          console.log('请选择上传的文件')
          return
        }
        // console.log(files.length)
        var fd = new FormData()
        for (let i = 0; i < files.length; i++) {
          fd.append('file', files[i])
        }
        // 创建xhr对象
        var xhr = new XMLHttpRequest()
        var url = 'http://localhost:9000/upload'
        xhr.open('POST', url, true)

        xhr.onreadystatechange = function () {
          if (xhr.readyState == 4 && xhr.status == 200) {
            var res = JSON.parse(xhr.responseText)
            console.log(res)
          }
        }
        //onprogress:进度监听事件,只要上传文件的进度发生了变化,就会自动的触发这个事件
        xhr.onprogress = updateProgress
        xhr.upload.onprogress = updateProgress

        function updateProgress(event) {
          // console.log(event)
          if (event.lengthComputable) {
            console.log(event.loaded)
            var completedPercent = ((event.loaded / event.total) * 100).toFixed(
              2
            )
            progressSpan.style.width = completedPercent + '%'
            progressSpan.innerHTML = completedPercent + '%'
            if (completedPercent > 90) {
              //进度条变色
              progressSpan.classList.add('green')
            }
            console.log('已上传', completedPercent)
          }
        }

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