在使用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>
效果如圖所示:

