(七)前端,如此简单!--- 四点读取
js中用于读取文件的,有四个核心类对象:
- Blob、File 承载数据
- ArrayBuffer 提供底层二进制视图
- FileReader 负责异步读取转换。
一、File
代表文件系统中的文件,继承自 Blob
constcontent="Hello, world!";constfile=newFile([content],"hello.txt",{type:"text/plain",lastModified:newDate().getTime(),});// 获取文件信息console.log("文件名:",file.name);// "hello.txt"console.log("文件大小:",file.size,"bytes");// 13bytesconsole.log("文件类型:",file.type);// "text/plain"console.log("最后修改时间:",newDate(file.lastModified));// 转换为可读时间 Mon May 01 2023 12:00:00 GMT+0800 (中国标准时间)二、ArrayBuffer
表示通用的、固定长度的原始二进制数据缓冲区
以字节粒度精确控制内存中的每一位数据
// 1. 创建 16 字节的缓冲区constbuffer=newArrayBuffer(16);//[0] [1] [2] [3] ... [15]// 2. 无符号8位整数数组,创建视图,关联到 bufferconstview=newUint8Array(buffer);view[0]=255;// 11111111view[1]=170;// 10101010view[15]=255;// 把第16个字节设置为255 ,8位二进制11111111console.log(view);// Uint8Array [255, 170, 0, ..., 255]//多个视图可以同时操作同一个 ArrayBuffer三、FileReader
异步读取 File 或 Blob 的内容
// 创建 FileReader 实例constreader=newFileReader();constinput=document.querySelector("input[type='file']");input.addEventListener('change',async(e)=>{constfile=e.target.files[0];if(!file)return;// 设置事件监听reader.onload=function(event){console.log('文件读取成功:',event.target.result);};reader.onerror=function(event){console.error('文件读取失败:',event.target.error);};reader.onloadstart=function(event){console.log('开始读取文件');};reader.onprogress=function(event){if(event.lengthComputable){constpercentLoaded=(event.loaded/event.total)*100;console.log(`加载进度:${percentLoaded.toFixed(2)}%`);}};reader.onloadend=function(event){console.log('读取完成(无论成功或失败)');};reader.onabort=function(event){console.log('读取被取消');};// FileReader 用于异步读取本地文件(如通过 File API),读取过程通常受本地 I/O 速度影响,不会因网络延迟而无限等待。因此没有定义 timeout 属性或 ontimeout 事件。// 一次只能执行一个读取操作,共有4种方法,选择一个执行reader.readAsText(file,'UTF-8');// 字符串 第一个参数 file 都是blob对象// reader.readAsArrayBuffer(file); // ArrayBuffer// reader.readAsDataURL(file); // Base64 Data URL// reader.readAsBinaryString(file); // 已废弃});XMLHttpRequest对象和FileReader对象都继承自EventTarget,
因此可以使用 addEventListener 或通过 onXXX 属性来绑定事件处理函数,监听异步操作的生命周期。
xhr.onload=()=>{...};// 或xhr.addEventListener('load',()=>{...});四、Blob
Binary Large Object,不可变的原始数据的类文件对象
consttextBlob=newBlob(['hello'],{// 通过构造函数将字符串转化为 Blobtype:'text/plain; charset=utf-8'})// Blob 方法console.log(textBlob.size);// 输出: 5 (因为 "hello" 是5个字节)console.log(textBlob.type);// 输出: "text/plain; charset=utf-8"console.log(textBlob);// 在控制台会显示: Blob(5) ["hello"]// 切片,且原始 Blob 不受影响constsliceBlob=textBlob.slice(0,5);// 'hello'// 转换为其他格式textBlob.text();// 'Hello World' 返回Promise解析为字符串textBlob.arrayBuffer();// ArrayBuffer 返回Promise解析为原始二进制数据// Blob 对象的 type只是元数据,读取时不会自动按类型解析,需要手动处理