Home  >  Article  >  Web Front-end  >  HTML5 new features: file and binary data operations

HTML5 new features: file and binary data operations

黄舟
黄舟Original
2017-03-30 13:02:352869browse

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.

var htmlParts = [&#39;<a id="a"><b id="b">hey!<\/b><\/a>&#39;];
var myBlob = new Blob(htmlParts, {&#39;type&#39;: &#39;text\/xml&#39;});

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

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

body.appendChild(a);
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);

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(&#39;POST&#39;, &#39;/server&#39;, true);
  xhr.onload = function(e) { ... };
  xhr.send(blobOrFile);
}

document.querySelector(&#39;input[type="file"]&#39;).addEventListener(&#39;change&#39;, 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);
(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 />
When the user selects the file, the file can be read.

var selected_file = document.getElementById(&#39;input&#39;).files[0];
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.

    // ...}
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;

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

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

下面是一个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;);
    };
}

下面是一个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;;
      }
    }
}

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

5、URL对象

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

var objecturl =  window.URL.createObjectURL(blob);

上面的代码会对二进制数据生成一个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);

下面是一个利用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);

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

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

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