前端访问文件夹

一共分为四个步骤

1.如何弹出文件夹选择框

<button>打开文件夹</button>
  <script>
    const btn = document.querySelector('button')
    btn.onclick = function ()
    {
//只需要这一个方法即可
      showDirectoryPicker()
    }
  </script>

这样就可以实现弹出文件夹

2.如何获取文件夹中的内容

<body>
  <button>打开文件夹</button>
  <script>
    const btn = document.querySelector('button')
    btn.onclick = async function ()
    {
      //句柄
      const handle = await showDirectoryPicker();
      await processHandle(handle);
      
    }
    async function processHandle (handle)
    {
      if (handle.kind === 'file') {
        return;
      }
      //entries ;异步迭代器还有一个values  可自行打印
      const entries = await handle.values();
      handle.children = []
      for await (const subHandle of entries) {
        handle.children.push(subHandle)
        await processHandle(subHandle)

      }
    }
  </script>
</body>

3.如何读取文件内容

<body>
  <button>打开文件夹</button>
  <script>
    const btn = document.querySelector('button')
    btn.onclick = async function ()
    {
      //句柄
      const handle = await showDirectoryPicker();
      await processHandle(handle);
      const fileHandle = handle.children[0];
      const file = await fileHandle.getFiles();
      const reader = new FileReader();
      reader.onload = (e) =>{
        console.log(e.target.value);
      }
      reader.readAsText(file);
      //可自行打印看
      console.log(handle);
    }
    async function processHandle (handle)
    {
      if (handle.kind === 'file') {
        return;
      }
      //entries ;异步迭代器还有一个values  可自行打印
      const entries = await handle.values();
      handle.children = []
      for await (const subHandle of entries) {
        handle.children.push(subHandle)
        await processHandle(subHandle)

      }
    }
  </script>
</body>

4.如何实现代码着色

可以直接用一个第三方库实现  highlight.js

这样就完成了!!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值