使用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>

效果如圖所示:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM