JS讀取本地文件



<!doctype html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>

</head>

<body>
    <div>
        <input type="file" id="files" style="display: none" onchange="fileImport();">
        <input type="button" id="fileImport" value="導入">
    </div>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <!-- <script src="../js/jQuery/jquery-1.11.1.js"></script> -->
    <script>
        //點擊導入按鈕,使files觸發點擊事件,然后完成讀取文件的操作
        $("#fileImport").click(function() {
            $("#files").click();
        })

        function fileImport() {
            //獲取讀取我文件的File對象
            var selectedFile = document.getElementById('files').files[0];
            var name = selectedFile.name; //讀取選中文件的文件名
            var size = selectedFile.size; //讀取選中文件的大小
            console.log("文件名:" + name + "大小:" + size);
            var reader = new FileReader(); //這是核心,讀取操作就是由它完成.
            reader.readAsText(selectedFile); //讀取文件的內容,也可以讀取文件的URL
            reader.onload = function() {
                //當讀取完成后回調這個函數,然后此時文件的內容存儲到了result中,直接操作即可
                console.log(this.result);
            }
        }


    </script>
</body>

</html>


免責聲明!

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



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