使用 jQuery 实现文件上传

<!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>
  <script src="js/jquery-3.6.0.js"></script>
</head>
<body>
  <input type="file" id="file1">
  <button id="btnUpload">上传文件</button>
  <br>
  <img src="img/loading.gif" alt="" style="display: none;" id="loading">

  <script>
    $(function () {
      // 监听到 Ajax 请求被发起了
      $(document).ajaxStart(function () {
        $('#loading').show()
      })
      // 监听到 Ajax 完成的事件
      $(document).ajaxStop(function () {
        $('#loading').hide()
      })

      $('#btnUpload').on('click', function () {
        // 核心代码
        let files = $('#file1')[0].files
        if (files.length <= 0) {
          return alert('请选择文件后再上传!')
        }

        let fd = new FormData()
        fd.append('avatar', files[0])

        // 发起 jQuery 的 Ajax 请求, 上传文件
        $.ajax({
          method: 'POST',
          url: 'http://www.liulongbin.top:3006/api/upload/avatar',
          data: fd,
          // 重要
          processData: false,
          contentType: false,
          success: function (res) {
            console.log(res);
          }
        })
      })
    })
  </script>
</body>
</html>

 

posted @ 2022-05-02 21:22  会前端的洋  阅读(343)  评论(0编辑  收藏  举报