js input file选择文件(此处以选择图片为例)

window.URL.createObjectURL    

可以用于在浏览器上预览本地图片或者视频。以图片为例,生成url

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>test</title>
  <style>
    *{
      list-style: none;
    }
    .img-item {
      position: relative;
     vertical-align: middle;
     width: 100px;
     height: auto;
     float: left;
    }
    .img-item  img{
      display: inline-block;
      width: 100%;
    }
  .close {
    position: absolute;
    right: 0;
    top:-5px;
    width: 20px;
    height: 20px;
  }
  </style>
</head>

<body>
  <input type="file" id='check' multiple>
  <!--multiple属性可以选择多张  -->
  <ul id='imgCon'></ul>
</body>

</html>
<script>
  var con = document.getElementById('check')
  var imgList = [] // 显示的图片
  con.onchange = function () {
    handleFile(con.files)
    // console.table(con.files)
  }

  function handleFile(files) {
    if (files.length + imgList.length > 4) {
      alert('最多4张') // 最多只能选四张,当前选中的和已显示之和不能大于4
      return
    }
    if (files[0]) {
      for (var i = 0; i < files.length; i++) {
        var img = window.URL.createObjectURL(files[i]) // 将文件生成url
        imgList.push(img)
      }
      show(imgList)
    }
  }

  function show(imgList) {
    var imgCon = document.getElementById('imgCon')
    var html = ''
    for (var i = 0; i < imgList.length; i++) {
      html += '<li class="img-item"><img src="' + imgList[i] + '" alt=""><span class="close" onclick="delImg(' + i +
        ')">X</span></li>'
    }
    imgCon.innerHTML = html
  }

  function delImg(index) { // 删除显示的图片
    console.log(con.files)
    imgList.splice(index, 1)
    show(imgList)
  }
</script>
原文地址:https://www.cnblogs.com/loya/p/10457196.html