通过 File System Access API 浏览器 读写本地文件

代码如下:

<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<button id="choose" >选择文件</button>
</body>
<script>
/**
* API参考地址:https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker
*/
document.getElementById('choose').onclick= async function(){
	
	var [fileHandle] = await window.showOpenFilePicker();
	
	var permission=await fileHandle.queryPermission();
	console.log(permission);

	//获取文件
	const file = await fileHandle.getFile();
	console.log(file);	
	
	//判断文件类型
	if (fileHandle.kind === 'file') {
	   console.log('this is file');
	} else if (fileHandle.kind === 'directory'){
		console.log('this is directory');
		return;
	}
	
	//读取文件内容
    var reader = new FileReader();  
	reader.onload = function() {  
		console.log( this.result);   
	}  
	reader.readAsText(file);  
		
	//创建写文件内容
    const writable = await fileHandle.createWritable();
	
	//写入内容到文件
    await writable.write("this david wirter file content:"+new Date().getTime());
	//关闭写入操作,否则内容不会写入到文件
    await writable.close();
			
}

</script>
</html>

API参考链接

https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker

注意事项:

1、授权无需预申请,在保存文件的时候会提示授权

2、发布部署时需要HTTPS才行

     本地调试使用localhost或者直接浏览器打开文件都可以

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值