Table of Contents
Blob (Binary Large
control
read the actual content of the file
5、URL对象
Home Web Front-end H5 Tutorial HTML5 new features: file and binary data operations

HTML5 new features: file and binary data operations

Mar 30, 2017 pm 01:02 PM

Historically, JavaScript cannot handle binary data. If it must be processed, only You can use the charCodeAt() method to convert text encoding into binary data byte by byte. Another way is to convert the binary data into Base64 encoding and then process it. These two methods are not only slow, but also error-prone. The Blob object is introduced to allow direct manipulation of binary data.

The Bolb object is a basic object representing binary data. Based on it, a series of related are derived. API, used to operate files

Blob (Binary Large

Object

) The object represents a piece of binary data and provides a series of operation interfaces. Other APIs for operating binary data (such as File objects) are based on the Blob object, inherits its Properties and methods. There are two ways to generate a Blob object: one is to use the Blob

constructor

, and the other is to use the slice method to cut an existing Blob object. Out part. (1) Blob constructor, accepts two parameters. The first parameter is an

array

containing the actual data, and the second parameter is the type of the data. None of the parameters are required.

The following is an example of using a Blob object to generate a downloadable file.

var blob = new Blob(['Hello World']);var a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.donwload = 'hello-world.txt';
a.textContent = 'Download Hello World';

body.appendChild(a);
Copy after login
The above code generates a hyperlink. After clicking, you will be prompted to download the text file hello-world.txt. The content of the file is "Hello World"

(2) The slice method of the Blob object divides the binary data into bytes and returns a new Blob object. .

var newBlob = oldBlob.slice(startingByte, endindByte);
Copy after login

The following is an example of using the XMLHttpRequest object to split a large file

for upload.

function upload(blobOrFile) {  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/server', true);
  xhr.onload = function(e) { ... };
  xhr.send(blobOrFile);
}

document.querySelector('input[type="file"]').addEventListener('change', function(e) {  
var blob = this.files[0];  
var BYTES_PER_CHUNK = 1024 * 1024; // 1MB chunk sizes.
  var SIZE = blob.size;  var start = 0;  
  var end = BYTES_PER_CHUNK;  while(start < SIZE) {
    upload(blob.slice(start, end));

    start = end;
    end = start + BYTES_PER_CHUNK;
  }
}, false);
Copy after login
(3) The Blob object has two read-only attributes:

size: The size of binary data, in bytes.
  • type: MIME type of binary data, all lowercase, if the type is unknown, the value is empty
  • String
  • .

    In Ajax operation, if xhr.responseType is set to blob, binary data is received.
2. FileList object

The FileList object is for the File

control

of the form. When the user selects a file through the file control, the value of the files attribute of this control is the FileList object. It is similar in structure to an array and contains multiple files selected by the user.

<input type="file" id="input" onchange="console.log(this.files.length)" multiple />
Copy after login
When the user selects the file, the file can be read.

var selected_file = document.getElementById(&#39;input&#39;).files[0];
Copy after login
Using drag and drop method, you can also get FileList object.

var dropZone = document.getElementById(&#39;drop_zone&#39;);
dropZone.addEventListener(&#39;drop&#39;, handleFileSelect, false);
function handleFileSelect(evt) {
    evt.stopPropagation();
    evt.preventDefault();    
    var files = evt.dataTransfer.files; // FileList object.

    // ...}
Copy after login
The handleFileSelect in the above code is the

callback function

of the drag and drop event. Its parameter evt is an event object, and the parameter's dataTransfer The .files property is a FileList object that contains the dragged and dropped files. 3. File object

The File object is a member of the FileList object and contains some meta-information about the file, such as file name, last modification time, file size and file type. Its attribute values ​​are as follows:

name: file name, this attribute is read-only
  • size: file size, in bytes, the Attribute read-only
  • #type: MIME type of the file. If the type cannot be distinguished, it will be an empty string. This attribute is read-only.
  • lastModifiedDate: The last modification time of the file. This attribute is read-only.
  • var selected_file = document.getElementById(&#39;input&#39;).files[0];
    var fileName = selected_file.name;
    var fileSize = selected_file.size;
    var fileType = selected_file.type;
    Copy after login

    4. FileReader object
The FileReader object receives a File object or Blob object as a parameter, which is used to

read the actual content of the file

, that is Read the contents of the file into memory. For different types of files, FileReader uses different methods to read.

  • FileReader.readAsBinaryString(Blob|File) :读取结果为二进制字符串,每个字节包含一个0到255之间的整数

  • FileReader.readAsText(Blob|File, opt_encoding) :读取结果是一个文本字符串。默认情况下,文本编码格式是'UTF-8',可以通过可选的格式参数,指定其他编码格式的文本。

  • FileReader.readAsDataURL(Blob|File) : 读取结果是一个基于Base64编码的 data-uri 对象。

  • FileReader.readAsArrayBuffer(Blob|File) :读取结果是一个 ArrayBuffer 对象。

FileReader采用异步方式读取文件,可以为一系列事件指定回调函数。

  • onabort:读取中断或调用reader.abort()方法时触发。

  • onerror:读取出错时触发。

  • onload:读取成功后触发。

  • onloadend:读取完成后触发,不管是否成功。触发顺序排在 onload 或 onerror 后面。

  • onloadstart:读取将要开始时触发。

  • onprogress:读取过程中周期性触发。

下面的代码是如何展示文本文件的内容。

var reader = new FileReader();

reader.onload = function(e){
       console.log(e.target.result);
}

reader.readAsText(blob);
Copy after login

onload事件的回调函数接受一个事件对象,该对象的target.result就是文件的内容。

下面是一个使用readAsDataURL方法,为img元素添加src属性的例子。

var reader = new FileReader();

reader.onload = function(e) {
    document.createElement(&#39;img&#39;).src = e.target.result;

};

reader.readAsDataURL(f);
Copy after login

下面是一个onerror事件回调函数的例子。

var reader = new FileReader();
reader.onerror = errorHandler;
function errorHandler(evt) {    
switch(evt.target.error.code) {      
case evt.target.error.NOT_FOUND_ERR:
        alert(&#39;File Not Found!&#39;);        
        break;      
        case evt.target.error.NOT_READABLE_ERR:
        alert(&#39;File is not readable&#39;);        
        break;      
        case evt.target.error.ABORT_ERR:        
        break;      
        default:
        alert(&#39;An error occurred reading this file.&#39;);
    };
}
Copy after login

下面是一个onprogress事件回调函数的例子,主要用来显示读取进度。

var reader = new FileReader();
reader.onprogress = updateProgress;function updateProgress(evt) {    
if (evt.lengthComputable) {      
var percentLoaded = Math.round((evt.loaded / evt.totalEric Bidelman) * 100);      
      var progress = document.querySelector(&#39;.percent&#39;);      
      if (percentLoaded < 100) {
        progress.style.width = percentLoaded + &#39;%&#39;;
        progress.textContent = percentLoaded + &#39;%&#39;;
      }
    }
}
Copy after login

读取大文件的时候,可以利用Blob对象的slice方法,将大文件分成小段,逐一读取,这样可以加快处理速度。

5、URL对象

URL对象用于生成指向File对象或Blob对象的URL。

var objecturl =  window.URL.createObjectURL(blob);
Copy after login

上面的代码会对二进制数据生成一个URL,类似于“blob:http%3A//test.com/666e6730-f45c-47c1-8012-ccc706f17191”。这个URL可以放置于任何通常可以放置URL的地方,比如img标签的src属性。需要注意的是,即使是同样的二进制数据,每调用一次URL.createObjectURL方法,就会得到一个不一样的URL。

这个URL的存在时间,等同于网页的存在时间,一旦网页刷新或卸载,这个URL就失效。除此之外,也可以手动调用URL.revokeObjectURL方法,使URL失效。

window.URL.revokeObjectURL(objectURL);
Copy after login

下面是一个利用URL对象,在网页插入图片的例子。

var img = document.createElement("img");

img.src = window.URL.createObjectURL(files[0]);

img.height = 60;

img.onload = function(e) {
    window.URL.revokeObjectURL(this.src);
}

body.appendChild(img);var info = document.createElement("span");

info.innerHTML = files[i].name + ": " + files[i].size + " bytes";

body.appendChild(info);
Copy after login

还有一个本机视频预览的例子。

var video = document.getElementById(&#39;video&#39;);var obj_url = window.URL.createObjectURL(blob);
video.src = obj_url;
video.play()
window.URL.revokeObjectURL(obj_url);
Copy after login

The above is the detailed content of HTML5 new features: file and binary data operations. 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.

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 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.

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.

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

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 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