Blob && File && Base64

126 阅读2分钟

基础

Blob

Blob对象表示一个不可变的、原始数据的类文件对象。

创建

const example = { hello: "world" };
const blob = new Blob([JSON.stringify(example, null, 2)], { type: 'application/json'})

属性

size 数据大小(字节) type 类型

方法

Blob.slice(start, ?end, contentType?) 返回一个新的Blob对象

Blob.stream() 返回一个能读取Blob内容的ReadableStream

Blob.text() 返回一个promise且包含Blob所有内容的UTF-8格式的USVString

const text = await blob.text(); // '{"hello":"world"}'

Blob.arrayBuffer() 返回一个promise且包含Blob所有内容的二进制格式的ArrayBuffer,需使用TypedArrayDataView来操作。

const buffer = await blob.arrayBuffer();
const byteOffset = 0;
const byteLength = 3;
const typedArray = new Int8Array(buffer, byteOffset, byteLength);
const typedArray2 = new Int16Array(buffer);
typedArray[1] = 42;
const dataView = new DataView(buffer, byteOffset, byteLength);
dataView.getInt8(3);
dataView.setInt16(1, 14);
dataView.getInt16(3);

获取

FileReader

创建

new FileReader()

属性

error 读取时的错误, readyState 'EMPTY'(0) 还未加载,'LOADING'(1) 加载中,'DONE'(2)加载完成, result读取的文件内容。

事件

onabort 中断事件 onerror 失败事件 onload 读取完成时触发 onloadstart 读取开始 onloadend 读取结束 onprogress 读取时

方法

FileReader.abort() 中断读取,返回'DONE'

FileReader.readAsArrayBuffer() resultArrayBuffer类型

FileReader.readAsDataURL() result中为URL格式的Base64字符串

FileReader.readAsText() result为字符串

URL

创建

new URL()

属性

hash:包含'#'USVString,后跟URL的片段标识符

host: 包含域名和端口号port(如果有的话)

href:完整的USVString

origin: 只读,包含协议名protocol、域名和端口号

pathname:以'/'开头紧跟URL文件路径的DOMString

search: 参数, '?'开头;searchParams只读

方法

toString() 返回整个URL 约等于href toJson() 同上

静态方法

URL.createObjectURL(FILE/BLOB): 创建一个以为的blob链接

URL.revokeObejectURL(url): 销毁之前创建的实例

图片时

createImageBitmap(image, sx?, sy?, sw?, sh?[, options]): 返回一个promise,其中image可以是<img>、SVG<image><video><canvas>BlobImageDataHTMLCanvasElement等,详见MDN

File

File对象是特殊类型的Blob,继承了Blob的功能并将其扩展使其支持用户系统上的文件,File可用在任意的Blob类型的context中。

创建

new File()

属性

lastModified 最后修改时间,字UNIX时间起始值以来的毫秒数

name 文件名称

size 文件大小

type 文件类型

方法

Blob.silce()

获取

const reader = new FileReader();
reader.onload = function() {};
reader.readAsDataURL(file)

Base64

Base64是一组相似的从二进制到文本的编码规则。

方法

atob() 解码

btoa() 编码, 如果有字符超出了8位ASCII编码的字符范围,会报错。

转化

tips:仅原理展示

// blob -> url
const url = URL.createObjectURL(blob);

// blob -> base64 
const reader = new FileReader();
reader.onload = function(e){ const result = e.target.result };
reader.readAsDataURL(blob);

// base64 -> blob URL.createObjectURL

集成

yarn add blob-url-file