记录一次前端上传按钮按钮样式修改及上传图片bs64处理

<!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;
    }

    #file {
     
     
      display: none;
    }

  </style>
</head>

<body>
  <div class="contains">
    <input type="file" id="file" />
    <button id="btn">上传文件</button>
  </div>
</body>
<script>
  const btn = document.getElementById('btn');
  const file = document.getElementById('file');
  btn.addEventListener('click', function () {
     
     
    // 让上传文件的按钮点击下
    file.click();
    // 监听改变
    file.addEventListener('change', function (e) {
     
     
      console.log(e.target.files[0]);
      const $file = e.target.files[0];
      // 文件转换为bs64
      let reader = new FileReader();
      reader.readAsDataURL($file)
      reader.onload = function (e) {
     
     
        console.log(e.currentTarget.result)
      }
    })
  })

</script>

</html>

猜你喜欢

转载自blog.csdn.net/kuangshp128/article/details/106617582
今日推荐