使用input的file进行上传进行预览

在使用file上传文件的时候,想到了图片预览的功能,然后查询了一些资料,一种是需要后端配合,将数据变成base64或者buff等数据传给后端然后调取接口进行显示,但是这种需要后端的配合和网络请求,感觉不如在纯前端操作方便的多,

话不多说,上代码:

<body>
<input type="file" class="inputFile">
<img class="showImg" alt="show-img"/>
</body>
<script>
  //改变上传图片的路径以便本地可以进行使用
  function getFileURL(file) {
    let getUrl = null;
    if (window.createObjectURL !== undefined) { // basic
      getUrl = window.createObjectURL(file);
    } else if (window.URL !== undefined) { // mozilla(firefox)
      getUrl = window.URL.createObjectURL(file);
    } else if (window.webkitURL !== undefined) { // webkit or chrome
      getUrl = window.webkitURL.createObjectURL(file);
    }
    return getUrl;
  }

  let fileElement = document.querySelector(".inputFile");//获得file的dom;
  let imgElement = document.querySelector(".showImg");//获得img的dom
  fileElement.onchange = function () {
    let url = getFileURL(fileElement.files[0]);//吧当前的files[0]传递进函数
    imgElement.setAttribute("src", url);//设置图片的src
  };

</script>

效果如图所示:

猜你喜欢

转载自www.cnblogs.com/mmykdbc/p/11003394.html