python前端显示本地文件内容
时间: 2023-11-09 12:49:54 浏览: 150
你可以使用 Python Flask 框架来搭建一个本地文件查看器的 Web 应用,然后在前端使用 Ajax 来调用后端接口获取文件内容并在页面中显示。
以下是基本代码示例:
后端代码:
```python
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/readfile')
def read_file():
filepath = request.args.get('filepath')
with open(filepath, 'r') as f:
content = f.read()
return jsonify({'content': content})
```
前端代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>本地文件查看器</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<form>
<label for="filepath">文件路径:</label>
<input type="text" id="filepath" name="filepath"><br><br>
<button type="button" onclick="readFile()">查看文件</button>
</form>
<br><br>
<div id="content"></div>
<script>
function readFile() {
var filepath = $('#filepath').val();
$.get('/readfile', {filepath: filepath}, function(data) {
$('#content').html(data.content);
});
}
</script>
</body>
</html>
```
你可以将以上代码保存为两个文件,分别为 `app.py` 和 `index.html`,然后在终端中运行 `python app.py` 命令启动应用,最后在浏览器中访问 `http://127.0.0.1:5000/` 即可打开本地文件查看器页面,输入文件路径并点击“查看文件”按钮,即可在页面上显示文件内容。
阅读全文
相关推荐


















