H5图片上传和预览

<!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>
</head>

<body>
  <input type="file" multiple class="file" accept="image/*">
  <img src="" alt="">
  <button>点击上传</button>
</body>
<script>
  var eleFile = document.querySelector('.file');
  var image = document.querySelector("img")
  var button = document.querySelector("button")
  // 压缩图片需要的一些元素和对象
  var targetWidth, targetHeight
  var reader = new FileReader(),
  img = new Image();

  // 选择的文件对象
  var file = null;

  // base64地址图片加载完毕后
  img.onload = function () {
    // 图片原始尺寸
    var originWidth = this.width;
    var originHeight = this.height;
    // 最大尺寸限制
    var maxWidth = 600,
      maxHeight = 500;
    // 目标尺寸
    targetWidth = originWidth,
      targetHeight = originHeight;
    // 图片尺寸超过400x400的限制
    if (originWidth > maxWidth || originHeight > maxHeight) {
      if (originWidth / originHeight > maxWidth / maxHeight) {
        // 更宽,按照宽度限定尺寸
        targetWidth = maxWidth;
        targetHeight = Math.round(targetWidth* (originHeight / originWidth));
      } else {
        targetHeight = maxHeight;
        targetWidth = Math.round(targetHeight* (originWidth / originHeight));
      }
    }
    image.width = targetWidth
    image.height = targetHeight
  };

  // 文件base64化,以便获知图片原始尺寸
  reader.onload = function (e) {
    img.src = e.target.result;
    image.src = e.target.result
  };
  eleFile.addEventListener('change', function (event) {
    file = event.target.files[0];
    // 选择的文件是图片
    if (file.type.indexOf("image") == 0) {
      reader.readAsDataURL(file);
    }
  });
  button.addEventListener('click', function () {
    if (!file) {
      return
    }
    var formData = new FormData()
    formData.append(file.name, file)
    uploadImage(formData)
  })

  function uploadImage(formdata) {
    // ....调用ajax上传图片
  }
</script>

</html>

猜你喜欢

转载自blog.csdn.net/gexiaopipi/article/details/79946157