美文网首页
前端js对象转为文件流 再转为js对象

前端js对象转为文件流 再转为js对象

作者: 喜欢走弯路的人 | 来源:发表于2024-12-26 16:42 被阅读0次

一、前端js 保存大文件的方法

代码如下

function saveFile(data, fileName) {

    const blob = new Blob([data], { type: 'application/octet-stream' });

    if (navigator.msSaveBlob) {

        // 兼容IE和Edge

        navigator.msSaveBlob(blob, fileName);

    } else {

        // 其他浏览器

        const link = document.createElement('a');

        link.href = URL.createObjectURL(blob);

        link.download = fileName;

        link.click();

        // 防止内存泄露

        setTimeout(() => URL.revokeObjectURL(link.href), 500);

    }

}

// 使用示例

const largeFile = new ArrayBuffer(1024 * 1024); // 假设这是一个大文件的ArrayBuffer数据

saveFile(largeFile, 'largeFile.bin'); // 保存文件为largeFile.bin

二、前端js对象转为文件流 再转为js对象

代码如下

// 假设我们有一个JS对象

varobj = {

    name:"John",

    age:30

};

// 将JS对象转换为文件流

functionobjectToFile(obj, fileName) {

    let json =JSON.stringify(obj);

    returnnewBlob([json], {type:'application/json'});

}

// 将文件流转换回JS对象

functionfileToObject(file) {

    letreader =newFileReader();

    reader.onload=function(e) {

        lettext = e.target.result;

        letobj =JSON.parse(text);

        // 处理转换后的对象

        console.log(obj);

    };

    reader.readAsText(file);

}

// 使用示例

letfile =objectToFile(obj,"data.json");

fileToObject(file);

相关文章

网友评论

      本文标题:前端js对象转为文件流 再转为js对象

      本文链接:https://www.haomeiwen.com/subject/sxiiejtx.html