web Front-end - Exploring HTML5 (3) FileReader

Posted by maplist on Tue, 16 Jul 2019 21:43:54 +0200

brief introduction

In HTML5, the file selection tag file adds the following two attributes:
- multiple: Setting the current element allows multiple files to be selected.
- accept: Sets the MIME type or suffix name that the current selector can choose.

<input type="file" multiple name="" id="myfilePhoto" value="" accept="image/jpg, image/png">

At the same time, FileReader objects appear. Using FileReader objects, web applications can read the contents of files (or raw data buffers) stored on the user's computer asynchronously. File objects or Blob objects can be used to specify the files or data to be processed.

FileReader: A constructor of a window object that reads the Dom e object of the File selected by the File Selection Label. That is to say, it is used to read the information selected by the file into memory and read the data in the file. Its interface provides an asynchronous API, which can be used to access the file system asynchronously in the browser's main thread and read the data in the file. For security, FileReader can read the selected files on the form and cannot read the local files. It reads the form files in the form of binary information: mainly for reading the information of large files.

Characteristic:

  1. After reading, the binary information is stored in the browser memory and transmitted to the server in batches.
  2. Usually with the background program, third-party plug-ins to complete together
  3. Breakpoint download and upload

Introduction to Use

Creating FileReader Objects

To create a FileReader object, it is very simple, as follows:

var fr = new FileReader();
FileReader's state constant:
Constant name value describe
EMPTY 0 No data has been loaded yet.
LOADING 1 Data is being loaded.
DONE 2 All read requests have been completed.
Method of FileReader Interface

The FileReader interface has five methods, four of which are used to read files and the other to interrupt reading. Regardless of success or failure, the method does not directly return the read result, which is stored in the result attribute.

FileReader interface method:

Method name parameter describe
readAsArrayBuffer file Read the file as an ArrayBuffer object to represent the contents of the read file.
readAsBinaryString file Read files as binary codes
readAsText file,[encoding] Read the file as text
readAsDataURL file Read the file as a Data URL, reading the local file path after encryption
abort (none) Terminal Read Operation
Properties of FileReader:
Property name type describe
error DOMError Error while reading file. Read-only.
readyState unsigned short Indicates the current state of the FileReader object. The value is one of the State constants. Read-only
result jsval The content of the read file. This property is valid only after the read operation is completed, and the format of the data depends on the method by which the read operation is initiated. Read-only.

FileReader interface events

The FileReader interface contains a complete set of event models for capturing the state of the file when it is read.

Events of the FileReader interface:

Event describe
onabort interrupt
onerror error
onloadstart start
onprogress Reading
onload Successful reading
onloadend Read completed, regardless of success or failure

Examples illustrate everything:

After talking about these, we still don't know how to use them. So, an example is given to illustrate everything.

<!-- multiple Multiple files -->
<input type="file" multiple name="" id="myfilePhoto" value="" accept="image/jpg, image/png">
<ul class="fileUl"></ul>
<script>
    document.getElementById('myfilePhoto').addEventListener("change",function(){
        var inputFile = document.getElementById('myfilePhoto');
        for(var i = 0; i<inputFile.files.length ;i++){
            var fr = new FileReader(); // This FileReader should correspond to the need to re-create a new file for each read file.
            var files = inputFile.files[i]; // Files can retrieve all the files selected in the current file input box and return the list.
            fr.readAsDataURL(files); // The read content is the local file path after encryption
            fr.onload = function(e){ // Trigger onload response function when data reading is completed
                // e.target is FileReader equivalent to fr
                var ulLi = document.createElement('li');
                var ulLiA = document.createElement('a');
                var ulLiimg = document.createElement('img');
                ulLiimg.src = e.target.result
                ulLiA.appendChild(ulLiimg);
                ulLi.appendChild(ulLiA);
                console.log(document.getElementsByClassName('fileUl'))
                document.getElementsByClassName('fileUl')[0].appendChild(ulLi)
            }       
        }
    });
</script>
<script>
    function updateSize() {
        var nBytes = 0;
        var oFiles = document.getElementById("uploadInput").files;
        var nFiles = oFiles.length;
        for (var nFileId = 0; nFileId < nFiles; nFileId++) {
            nBytes += oFiles[nFileId].size;
        }
        var sOutput = nBytes + " bytes";
        var aMultiples = ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"];
        var nMultiple = 0, nApprox = nBytes / 1024;

        for ( ; nApprox > 1; nApprox /= 1024, nMultiple++) {
            sOutput = nApprox.toFixed(3) + " " + aMultiples[nMultiple] + " (" + nBytes + " bytes)";
        }

        document.getElementById("fileNum").innerHTML = nFiles;
        document.getElementById("fileSize").innerHTML = sOutput;
    }
</script>
<p>
    <input id="uploadInput" type="file" name="myFiles" onchange="updateSize();" multiple>
    //Number of files selected:<span id="fileNum">0</span>
    //Total size:<span id="fileSize">0</span>
</p>

Note: Putting var fileReader = new FileReader(); out of the loop leads to Uncaught InvalidStateError: Failed to execute `readAs Data URL'on `FileReader': The object is already busy reading Blobs. Error, this FileReader should correspond to each read file that needs to be heavy. New one.
Onload is triggered only when all data reads are successfully completed, and the result is only after onload.

Use of FileReader Interface

At the end of the example, another big case:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script type="text/javascript">  
        var result=document.getElementById("result");  
        var file=document.getElementById("file");  

        //Determine whether the browser supports the FileReader interface  
        if(typeof FileReader == 'undefined'){  
            result.InnerHTML="<p>Your browser does not support it FileReader Interface!</p>";  
            //Make the selection control inoperable  
            file.setAttribute("disabled","disabled");  
        }  

        function readAsDataURL(){  
            //Verify that it is an image file  
            var file = document.getElementById("file").files[0];  
            if(!/image\/\w+/.test(file.type)){  
                alert("See clearly, this needs pictures!");  
                return false;  
            }  
            var reader = new FileReader();  
            //Read files into pages as data URLs  
            reader.readAsDataURL(file);  
            reader.onload=function(e){  
                var result=document.getElementById("result");  
                //Display files  
                result.innerHTML='![](' + this.result +')';  
            }  
        }  

        function readAsBinaryString(){  
            var file = document.getElementById("file").files[0];  
            var reader = new FileReader();  
            //Read files into pages in binary form  
            reader.readAsBinaryString(file);  
            reader.onload=function(f){  
                var result=document.getElementById("result");  
                //Display files  
                result.innerHTML=this.result;  
            }  
        }  

        function readAsText(){  
            var file = document.getElementById("file").files[0];  
            var reader = new FileReader();  
            //Read the file into the page as text  
            reader.readAsText(file);  
            reader.onload=function(f){  
                var result=document.getElementById("result");  
                //Display files  
                result.innerHTML=this.result;  
            }  
        }  
    </script>  
    <p>  
        <label>Please select a file:</label>  
        <input type="file" id="file" />  
        <input type="button" value="Read the image" onclick="readAsDataURL()" />  
        <input type="button" value="Read binary data" onclick="readAsBinaryString()" />  
        <input type="button" value="Read text files" onclick="readAsText()" />  
    </p>  
    <div id="result" name="result"></div>
</body>
</html>

Topics: html5 Attribute encoding Javascript