HTML5 之 FileReader 方法上傳並讀取文件


原文地址:https://caochangkui.github.io/file-upload/

HTML5 的 FileReader 對象允許Web應用程序異步讀取存儲在用戶計算機上的文件(或原始數據緩沖區)的內容,使用 File 或 Blob 對象指定要讀取的文件或數據。

FileReader 事件

  • FileReader.onabort
    處理abort事件。該事件在讀取操作被中斷時觸發。

  • FileReader.onerror
    處理error事件。該事件在讀取操作發生錯誤時觸發。

  • FileReader.onload
    處理load事件。該事件在讀取操作完成時觸發。

  • FileReader.onloadstart
    處理loadstart事件。該事件在讀取操作開始時觸發。

  • FileReader.onloadend
    處理loadend事件。該事件在讀取操作結束時(要么成功,要么失敗)觸發。

  • FileReader.onprogress
    處理progress事件。該事件在讀取Blob時觸發。


用法

下面分別是上傳csv文件和圖片文件的兩種用法:
html部分

<div style="border: 1px solid red;">
    <h2>上傳CSV文件</h2>
    <input type="file" id="file" accept=".csv" onchange="uploadfile();" />
    <div id="result"> </div>
</div>

<br>
<br>

<div style="border: 1px solid red;">
    <h2>上傳圖片</h2>
    <input type="file" id="file2" accept="image/*" onchange="uploadfile2();" />
    <div id="result2">
        <img src="" alt="" id="img">
    </div>
</div>

js部分

<script>
    // 上傳csv格式的文件
    function uploadfile() {
        let reads = new FileReader();
        file = document.getElementById('file').files[0];
        reads.readAsText(file, 'utf-8');
        console.log(reads);
        reads.onload = function (e) {
            console.log(e)
            // document.getElementById('result').innerText = this.result
            document.getElementById('result').innerText = e.target.result
        };
        reads.onloadstart = function(e) {
            console.log('onloadstart ---> ', e)
        }
        reads.onloadend = function(e) {
            console.log('onloadend ---> ', e)
        }
        reads.onprogress = function(e) {
            console.log('onprogress ---> ', e)
        }
    }

    // 上傳image
    function uploadfile2() {
        let reads = new FileReader();
        file = document.getElementById('file2').files[0];
        reads.readAsDataURL(file);
        console.log(reads);
        reads.onload = function (e) {
            document.getElementById('img').src = this.result;
        };
    }
</script>


免責聲明!

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



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