Home  >  Article  >  Web Front-end  >  HTML5 FileAPI graphic and text code sharing

HTML5 FileAPI graphic and text code sharing

黄舟
黄舟Original
2017-03-28 16:00:281726browse

In HTML5, a API about file operations is provided. Through this API, related processing of accessing the local file system from the web page becomes very simple. So far only some browsers support it.

1.FileListObject and File object

The FileList object represents the file list selected by the user, in HTML4 Only one file is allowed to be placed in the file control, but in HTML5, multiple files are allowed to be placed in the file control by adding the multiple attribute. Each file selected by the user in the control is a file object, and FileList is a list of these file objects, representing all the files selected by the user. The file object has two attributes, one is name, which means the file name does not include the path of the file; the other is lastModifiedDate, which means the date the file was last modified.

<!DOCTYPE html>
<html>
    <head>
        <meta charset=&#39;UTF-8&#39;/>
        <title>FileList and File </title>
        <script type="text/javascript" language="JavaScript">
function showFiles(){
var file,
                len = document.getElementById(&#39;file&#39;).files.length;//返回FileList文件列表对象
for (var i=0; i < len; i++) {
                  file = document.getElementById(&#39;file&#39;).files[i];
                  alert(file.name);
                };
                
            }            
</script>               
    </head>
    <body>
        <input type="file" id=&#39;file&#39; multiple="multiple" width="80px"/>
        <input type="button" id="bt1" value="click" onclick="showFiles();"/>
    </body>
</html>

2.Blob object

When it comes to Blob objects, some people may think of the Blob fields in OracleDB, which are somewhat similar in meaning. Blob in HTML5 represents binary raw data. It provides a slice() method through which you can access the raw data block inside the bytes. In fact, the file object mentioned above inherits the Blob object.

Two attributes of the Blob object, size: represents the byte length of an object. type: Represents the MIME type of an object. If it is an unknown type, an empty

string is returned.

function showFileInfo(){
                var file = document.getElementById(&#39;file&#39;).files[0];
                var size = document.getElementById(&#39;fileType&#39;);
                var type = document.getElementById(&#39;fileSize&#39;);
                size.innerHTML = file.size;
                type.innerHTML = file.type;
            }

For image type files, the type attribute of the Blob object starts with image/. This feature can be used to determine the file type selected by the user.

function showFileInfo(){
                var file = document.getElementById(&#39;file&#39;).files[0];
                if(checkImage(file)){
                var size = document.getElementById(&#39;fileType&#39;);
                var type = document.getElementById(&#39;fileSize&#39;);
                size.innerHTML = file.size;
                type.innerHTML = file.type;
                }
                else{
                    return ;
                }
            }
            function checkImage(file){
                if(!/img\/\w+/.test(file.type)){
                    alert(file.name + "不是图片");
                    return false;
                }
                return true;
            }

In addition, the file control adds the accept attribute in the HTML5 standard to limit the file types accepted, but currently the alignment support of each browser is limited to the default selection of image files when opening the file selection window. , if you choose other types, the control can also accept it.

3.FileReader interface

3.1 Interface methods

The FileReader interface provides four methods, 3 of which are used to

read files, 1 Used to interrupt file reading.

Method nameParametersDescriptionreadAsBinaryString()fileRead the file as a binary string, usually pass it to the backend, the backend can store the file through this stringreadAsDataURL( )file Read the file as a data url string. In fact, the small file is directly read into the page with a URL address in a special format. Small files usually refer to files in formats such as images and htmlreadAsText()file [encoding]Read the file as text, The second parameter is the encoding of the text. abort()(none)Abort the read operation.

It should be noted that whether the read is successful or failed, the method will not return Read the result and return the result in the result attribute.

 3.2 Interface

Event

The FileReader interface provides a complete set of event models for capturing the status when reading files.

EventDescriptiononabortOccurs when data reading is interruptedonerrorOccurs when data reading erroronloadstartOccurs when data reading startsonloadOccurs when the data read is completed successfullyonloadendOccurs when the data read is completed regardless Reading success or failureonprogessData reading
 3.3 Example

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <title>FileReader</title>
        <meta name="description" content="" />
        <meta name="viewport" content="width=device-width; initial-scale=1.0" />
        <script type="text/javascript" language="JavaScript">
var file ,
                result; 
function  myLoad() {
                 file = document.getElementById(&#39;file&#39;).files[0];
                 result = document.getElementById(&#39;result&#39;);
            }
if(typeof FileReader == &#39;undefined&#39;){
                result.innerHTML = "你的浏览器不支持 FileReader";
                file.setAttribute("disabled","disabled");
            }
function readAsDataURL(){
if(!/image\/\w+/.test(file.type)){
                    alert(file.name + &#39;不是一个图片类型的文件&#39;);
                }else{
var reader = new FileReader();
                    reader.readAsDataURL(file);
                    reader.onload = function(e){
                        
                        result.innerHTML = "<img src=" + reader.result +"/>";
                    };
                }
            }
function readAsBinaryString(){
var reader = new FileReader();
                reader.readAsBinaryString(file);
                reader.onload = function(e){                    
                    result.innerHTML = reader.result;
                };
            }
function readAsText(){
var reader = new FileReader();
                reader.readAsText(file);
                reader.onload=function(e){                                       
                    result.innerHTML = reader.result;
                };
            }
</script>

    </head>
    <body onload="myLoad();">
        <p>
            <input type="file" id=&#39;file&#39;/>
            <input type=&#39;button&#39; id="bt_DataURL" value="读取图片" onclick="readAsDataURL();"/>
            <input type="button" id="bt_BinaryString" value="读取二进制字符串" onclick="readAsBinaryString();"/>
            <input type="button" id="bt_textString" value="读取文本信息" onclick="readAsText();"/>
        </p>   
        <div id="result">
            
        </div>
    </body>
</html>

The above is the detailed content of HTML5 FileAPI graphic and text code sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn