Home >Web Front-end >H5 Tutorial >HTML5 new features: file and binary data operations
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
) 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 = ['<a id="a"><b id="b">hey!<\/b><\/a>'];
var myBlob = new Blob(htmlParts, {'type': 'text\/xml'});
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);
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('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);(3) The Blob object has two read-only attributes: size: The size of binary data, in bytes.
<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('input').files[0];Using drag and drop method, you can also get FileList object.
var dropZone = document.getElementById('drop_zone'); dropZone.addEventListener('drop', 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-onlyvar selected_file = document.getElementById('input').files[0]; var fileName = selected_file.name; var fileSize = selected_file.size; var fileType = selected_file.type;4. FileReader object
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('img').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('File Not Found!'); break; case evt.target.error.NOT_READABLE_ERR: alert('File is not readable'); break; case evt.target.error.ABORT_ERR: break; default: alert('An error occurred reading this file.'); }; }
下面是一个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('.percent'); if (percentLoaded < 100) { progress.style.width = percentLoaded + '%'; progress.textContent = percentLoaded + '%'; } } }
读取大文件的时候,可以利用Blob对象的slice方法,将大文件分成小段,逐一读取,这样可以加快处理速度。
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('video');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!