Home Web Front-end H5 Tutorial HTML5 FileAPI graphic and text code sharing

HTML5 FileAPI graphic and text code sharing

Mar 28, 2017 pm 04:00 PM

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>
Copy after login

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;
            }
Copy after login

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;
            }
Copy after login

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>
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles