Blob
A Blob object represents a file-like object of immutable, primitive data. Its data can be read in text or binary format, and can also be converted into a ReadableStream for data manipulation.
To construct a Blob from other non- Blob objects and data , use the Blob() constructor. To create a subset of a Blob's data , use the slice() method.
Blob constructor: Blob(blobParts[, options]) , which allows creating Blob objects from other objects . For example, to build a Blob out of strings :
var debug = {hello: "world"};
var blob = new Blob([JSON.stringify(debug, null, 2)], {type : 'application/json'});
Attributes | describe |
---|---|
size | The size (in bytes) of the data contained in the Blob object |
type | A string indicating the MIME type of the data contained in this Blob object. If the type is unknown, the value is the empty string. |
method | describe |
---|---|
Blob.slice([start[, end[, contentType]]]) | Returns a new Blob object containing the data within the specified range of the source Blob object |
Blob.stream() | Returns a ReadableStream that can read the content of the blob |
Blob.text() | Returns a promise containing a USVString in UTF-8 format containing the entire content of the blob |
Blob.arrayBuffer() | Returns a promise containing an ArrayBuffer in binary format containing all the contents of the blob |
File
Typically, the File object is the FileList object returned after the user selects a file on an <input> element .
File objects are a special type of Blob that can be used in any Blob- type context . For example: FileReader , URL.createObjectURL() , createImageBitmap() , and XMLHttpRequest.send() can handle Blob and File .
File property:
Attributes | describe |
---|---|
lastModified | Returns the last modification time (in milliseconds) of the file referenced by the current File object |
lastModifiedDate | Returns the Date object of the last modification time of the file referenced by the current File object |
name | Returns the name of the file referenced by the current File object |
size | Returns the size of the file referenced by the current File object |
type | Returns the Multipurpose Internet Mail Extensions type (MIME Type) of the file referenced by the current File object |
webkitRelativePath | Returns the path or URL associated with the file referenced by the current File object |
File methods: The File interface does not define any methods, but it inherits the following method from the Blob interface: Blob.slice([start[, end[, contentType]]])
FileReader
HTML5 's FileReader API allows the client browser to read the user's local files, so that it is no longer necessary to upload files to be read by the server, which greatly reduces the burden on the server and saves the time required for uploading files. According to the definition of W3C , the FileReader interface provides a method for reading files and an event model including the reading results.
1. Detect browser support for FileReader
if (window.FileReader) {
var fr = new FileReader();
// add your code here
} else {
alert("Not supported by your browser!");
}
2. Call the method of the FileReader object
An instance of FileReader has 5 methods, 4 of which are used to read the file and one is used to interrupt the reading. The table below lists these methods along with their parameters and functions. After the file is read, no matter whether the reading succeeds or fails, the method will not return the reading result.
method name | parameter | describe |
---|---|---|
abort | none | interrupt read operation |
readAsText | Blob or File , [encoding] | read the file as text |
readAsArrayBuffer | Blob or File | read text as arraybuffer |
readAsBinaryString | Blob or File | Read a file as binary code (deprecated) |
readAsDataURL | Blob or File | Read file as DataURL |
readAsText: This method can convert Blob or File objects into content (string form) according to a special encoding format, where the second parameter is the encoding method of the text, and the default value is UTF-8 .
readAsBinaryString: This method has been removed from the FileAPI standard, please use readAsArrayBuffer instead.
readAsDataURL: This method reads the file as a string in data :
URL format ( base64 encoding). The essence of this string is Data URL . Data URL is a solution for directly embedding small files into documents. The small files here usually refer to files in formats such as images and html .
3. Handling events
FileReader includes a complete set of event models for capturing the status of reading files, the following table summarizes these events.
event | describe |
---|---|
onabort | triggers on interrupt |
onerror | fires on error |
onload | Fired when a file read completes successfully |
onloadend | Read completion fires, either success or failure |
onloadstart | Triggered when reading starts |
onprogress | Loading |
4. Obtain the file reading result
After the file reading operation is performed, the reading result is stored in the result property of the created FileReader object , or the reading result can be obtained by listening to the processing event, and the result is stored in the ProgressEvent.target.result property . For details, see the following file reading example:
<html>
<head>
<title>FileReader</title>
<label class="btn" for="uploads">选择文件</label>
<input type="file" id="uploads" style="position:absolute; clip:rect(0 0 0 0);" onchange="selectfile(event)">
<style>
.btn {
position:relative;
left:50%;
top:50%;
font-size: 12px;
border-radius: 3px;
color: #fff;
background-color: #409EFF;
padding: 8px 15px;
}
</style>
</head>
<body>
<script>
function selectfile (e) {
let file = e.target.files[0]
// 创建 FileReader 对象
let fr = new FileReader()
fr.readAsDataURL(file)
fr.onload = (ProgressEvent) => {
let data = ProgressEvent.target.result;
alert("读取文件结果:" + data)
}
}
</script>
</body>
</html>
convert
Convert base64 string to Blob object:
/**
* @param {String} dataurl 完整的base64字符串
* @return: Blob 对象
*/
dataURLtoBlob(dataurl) {
var arr = dataurl.split(',');
var mime = arr[0].match(/:(.*?);/)[1];
var bstr = atob(arr[1]);
var n = bstr.length;
var u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
The base64 string is converted into a Blob string, and the Blob string can be used like a normal URL , such as on img.src .
/**
* @param {String} base64 base64字符串
* @return: Blob 字符串,可以直接用作下载路径url
*/
createDownloadBlobUrl(base64) {
const blob = this.dataURLtoBlob(base64);
return URL.createObjectURL(blob);
}
Convert between ArrayBuffer and Blob objects
// arrayBuffer 转换成 blob
let blob = new Blob(arraybuffer)
// blob 转换成 arrayBuffer
blob.arrayBuffer().then(arraybuffer => {
// do something...
})