目录
- 说在前面
- FileReader
- DOMParser
- 文本文件
- 二进制文件
说在前面
- 浏览器版本:Microsoft Edge 126.0.2 (正式版本) (64 位)
FileReader
- MDN
FileReader
接口允许 Web 应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,使用File
或Blob
对象指定要读取的文件或数据。
DOMParser
- MDN
DOMParser
可以将存储在字符串中的XML
或HTML
源代码解析为一个DOM Document
。
文本文件
- 以
xml
文件为例 vue
<script setup>function btnClick() {document.getElementById("file1").click() }function openFile(e) {var file = e.target.files[0]var reader = new FileReader()reader.onload = function(e) {var content = e.target.resultvar parser = new DOMParser()var xmlDoc = parser.parseFromString(content, "text/xml")console.log(xmlDoc)}reader.readAsText(file) } </script><template><button @click="btnClick">Open</button><input id="file1" type="file" style="display:none" @change="openFile"> </template>
- 结果
二进制文件
- 以
navmesh
为例<script setup> import * as THREE from 'three'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'; import {init as initRecastNavigation,NavMeshQuery, } from '@recast-navigation/core'; import { generateSoloNavMesh } from '@recast-navigation/generators'; import { DebugDrawer, getPositionsAndIndices } from '@recast-navigation/three'; import { exportNavMesh, importNavMesh } from 'recast-navigation';// initialise recast-navigation initRecastNavigation();// setup scene const renderer = new THREE.WebGLRenderer(); document.body.appendChild(renderer.domElement);const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(); camera.position.set(10, 10, -10);const orbitControls = new OrbitControls(camera, renderer.domElement);// handle resizing const onWindowResize = () => {camera.aspect = window.innerWidth / window.innerHeight;camera.updateProjectionMatrix();renderer.setSize(window.innerWidth, window.innerHeight); }; onWindowResize();window.addEventListener('resize', onWindowResize);// animate const animate = () => {requestAnimationFrame(animate);renderer.render(scene, camera); };animate();function btnClick() {document.getElementById('file1').click(); }function openBinFile(e) {var file = e.target.files[0];var reader = new FileReader();reader.onload = function (e) {var content = new Uint8Array(e.target.result);const { navMesh } = importNavMesh(content);const debugDrawer = new DebugDrawer();debugDrawer.drawNavMesh(navMesh);scene.add(debugDrawer);console.log(content);};reader.readAsArrayBuffer(file); } </script><template><button @click="btnClick">Open</button><input id="file1" type="file" style="display: none" @change="openBinFile" /> </template>
- 结果