Node.js中本地Excel文件转Blob遇类型不兼容错误求助
如何将本地Excel文件转换为Blob?
我正在读取本地Excel文件,并尝试将其转换为Blob。当前使用的代码如下:
const data = fs.readFileSync('./mybook.xlsx', {encoding:'base64'}); const base64 = base64ToBlob(data) const blob = new Blob(base64, {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
运行后出现如下错误:
Argument type Blob is not assignable to parameter type BlobPart[] | undefined
Type Blob is not assignable to type BlobPart[]
Type Blob is not assignable to type Array
请问是否可以实现该转换?
当然可以实现,问题出在代码逻辑的冗余和参数类型不匹配上:
错误根源:
base64ToBlob的返回值已经是一个Blob对象,但你又把它传给new Blob()构造函数——而Blob构造函数的第一个参数要求是BlobPart数组(如字符串、ArrayBuffer、TypedArray等),直接传Blob对象自然会触发类型不匹配错误。两种可行修正方案:
方案一:直接复用base64ToBlob的结果
如果base64ToBlob能正确生成对应MIME类型的Blob,无需再调用new Blob():
const data = fs.readFileSync('./mybook.xlsx', {encoding:'base64'}); // 确保base64ToBlob支持传入MIME类型参数,或内部已正确设置类型 const blob = base64ToBlob(data, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
方案二:手动从Buffer转换为Blob(无需依赖base64ToBlob)
直接读取文件为Buffer再转ArrayBuffer,是更高效的方式:
const fs = require('fs'); // 直接读取文件为Buffer const buffer = fs.readFileSync('./mybook.xlsx'); // 将Node.js Buffer转换为标准ArrayBuffer const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength); // 基于ArrayBuffer创建Blob const blob = new Blob([arrayBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
内容的提问来源于stack exchange,提问作者TommyD
相关产品推荐
相关产品推荐

