思路
通过window自带的 window.showOpenFilePicker, window.showSaveFilePicker进行上传文件和保存文件可以设置文件保存名称和type类型具体操作看官网获取
打开文件操作
[this.fileHandle] = await window.showOpenFilePicker({
excludeAcceptAllOption: true, // 是否排除“所有文件”选项
types: [
{
description: 'JSON', // 文件类型描述
accept: {
'json/plain': ['.json'], // 文件 json 类型及其对应的扩展名
},
}
],
});//很关键需要存入到全局变量用于保存使用
this.fileBlob = await this.fileHandle.getFile()
var reader = new FileReader();//这里是核心!!!读取操作就是由它完成的。
reader.readAsText(this.fileBlob);//读取文件的内容
const that = this
reader.onload = function(){
const compressedData = Buffer.from(this.result, 'base64');
}
保存文件操作
newFileHandler方法
async function newFileHandler() {
const options = {
suggestedName: `name.json`, //文件名称
excludeAcceptAllOption: true, // 是否排除“所有文件”选项
types: [
{
description: "确认保存文件",
accept: {
'json/plain': ['.json'],
},
},
],
};
return await window.showSaveFilePicker(options);
}
//当fileHandle不存在时需要打开弹窗进行保存
if(!this.fileHandle){
this.fileHandle = await newFileHandler()
}
const writable = await this.fileHandle.createWritable();
// 通过管道将数据传输到文件
await writable.write(buffer.toString('base64'));
// 管道使用完毕后需要关闭
await writable.close();
另存文件(直接去除判断走newFileHandler方法即可)
this.fileHandle = await newFileHandler()
const writable = await this.fileHandle.createWritable();
// 通过管道将数据传输到文件
await writable.write(buffer.toString('base64'));
// 管道使用完毕后需要关闭
await writable.close();
总结
该方法在web端, 首次进入页面需要用户确定给该ip写入权限之后才能进行保存操作,否者无法直接写入客户端电脑磁盘里面(方法仅在浏览器环境中使用,在node环境中不允许使用)