在写html时,用浏览器读取本地文件
前言
- 浏览器没有读取本地文件的权限,如果有这个权限,本地文件会特别不安全。
- 通过http服务器实现
- 用txt文件举例
解决方法
在本地搭建一个简单的HTTP服务器,然后通过网络协议来访问本地的a.txt文件。这样就可以使用JavaScript从服务器请求文件并在HTML页面中显示它。一种简单的方法是使用 Node.js 的 http-server 模块或者 Python 的 SimpleHTTPServer 模块来启动一个本地服务器。
准备工作
- index.html(空文件)
- a.txt(任意内容)
实际操作
- 安装 Node.js(下载20.10.0版本)
- 在存放a.txt文件的目录下,打开命令行并安装一个简单的HTTP服务器,例如http-server模块:
npm install -g http-server
- 在命令行中进入存放a.txt文件的目录,然后运行以下命令启动HTTP服务器:
http-server
- 在浏览器中打开 http://localhost:8080 (或其他指定的端口),你将会看到目录列表,包括a.txt文件。
- 在index.html的HTML文件中,写入以下代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Display a.txt Content</title>
</head>
<body>
<div id="content"></div>
<script>
fetch('http://localhost:8080/a.txt')
.then(response => response.text())
.then(data => {
document.getElementById('content').innerText = data;
});
</script>
</body>
</html>
- 打开http://localhost:8080后,即可看到a.txt内容显示在网页里。
发布者:admin,转转请注明出处:http://www.yc00.com/web/1741135181a4312859.html
评论列表(0条)