from flask import Flask, send_from_directory app = Flask(name) @app.route('/file') def get_file(): return send_from_directory('D:/gangko') if name == 'main': app.run(host='192.168.1.226', port=8000, debug=True)给出这段代码对应的前端代码,可以访问目录中文件
时间: 2023-12-09 09:03:08 浏览: 45
这段代码是后端代码,用于提供接口让前端调用。如果你想让前端通过浏览器访问该接口并获取 `D:/gangko` 目录下的文件,可以编写以下前端代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Get File</title>
</head>
<body>
<button onclick="getFile()">Get File</button>
<script>
function getFile() {
window.location.href = '/file?filename=test.txt';
}
</script>
</body>
</html>
```
这段代码会在页面上显示一个按钮,当点击该按钮时,会向 `/file` 路径发送请求,并将 `filename` 参数设置为 `test.txt`。后端代码可以根据该参数来返回指定的文件。需要注意的是,这段代码使用了 `window.location.href` 来导航到指定的 URL,这会导致浏览器重新加载页面。如果你希望在不刷新页面的情况下获取文件内容,可以使用 JavaScript 的 `fetch` 函数。
相关问题
from flask import Flask, send_from_directory app = Flask(__name__) @app.route('/file') def get_file(): return send_from_directory('D:/gangko') if __name__ == '__main__': app.run(host='192.168.1.226', port=8000, debug=True)给出这段代码对应的前端代码
这段代码是后端代码,用于提供接口让前端调用。如果你想让前端通过浏览器访问该接口并获取 `D:/gangko` 目录下的文件列表,你可以编写以下前端代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Get File List</title>
</head>
<body>
<button onclick="getFileList()">Get File List</button>
<ul id="file-list"></ul>
<script>
function getFileList() {
fetch('/file')
.then(response => response.json())
.then(data => displayFileList(data))
.catch(error => console.error(error));
}
function displayFileList(data) {
const fileList = document.getElementById('file-list');
fileList.innerHTML = '';
data.forEach(file => {
const li = document.createElement('li');
li.innerText = file;
fileList.appendChild(li);
});
}
</script>
</body>
</html>
```
这段代码会在页面上显示一个按钮,当点击该按钮时,会向 `/file` 路径发送请求,然后将响应内容解析为 JSON,最后将文件列表显示在页面上。需要注意的是,这段代码假设响应内容是一个 JSON 数组,其中包含了文件列表。你可以根据需要修改代码,以便显示其它类型的数据。
flask send_from_directory与send_file在传递文件的区别
在 Flask 中,`send_from_directory` 和 `send_file` 都用于向客户端文件,但有一些区别。
send_from_directory` 函数用于从指定目录中发送文件。它提供了方便的方式来发送静态文件,如图像、CSS、JavaScript 等。以下是一个示例代码:
```python
from flask import Flask, send_from_directory
app = Flask(__name__)
@app.route('/images/<path:filename>')
def get_image(filename):
# 从指定目录中发送文件
return send_from_directory('static/images', filename)
if __name__ == '__main__':
app.run()
```
在上面的示例中,当请求 `/images/filename.jpg` 时,`get_image` 函数会从 `static/images` 目录中发送名为 `filename.jpg` 的文件。
`send_file` 函数用于发送任意类型的文件。它可以发送动态生成的文件(如通过 Pandas 导出的 XLSX 文件),或者从任意路径中发送文件。以下是一个示例代码:
```python
from flask import Flask, send_file
import pandas as pd
app = Flask(__name__)
@app.route('/api/export')
def export_data():
# 生成文件或从文件路径中获取文件
# ...
# 发送文件
return send_file('path/to/file.xlsx', as_attachment=True)
if __name__ == '__main__':
app.run()
```
在上面的示例中,当请求 `/api/export` 时,`export_data` 函数会发送名为 `file.xlsx` 的文件。
总结来说,`send_from_directory` 适用于发送静态文件,而 `send_file` 则适用于发送各种类型的文件,包括动态生成的文件。根据你的需求选择合适的函数。